当前位置:网站首页>力扣242-有效的字母异位词——哈希表法
力扣242-有效的字母异位词——哈希表法
2022-08-09 04:53:00 【张怼怼√】
题目描述
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
注意:若 s 和 t 中每个字符出现的次数都相同,则称 s 和 t 互为字母异位词。
求解思路
- 创建一个大小为26的数组arr,用于存储每个字母在字符串中出现的次数;
- 首先遍历字符串s,统计s中各个字母的出现次数(次数更新+1);
- 接下来遍历字符串t(次数更新-1);
- 最后看arr中所有元素是否都为0;
- 如果都为0,说明 s 和 t 是字母异位词,返回 true ,反之则返回 false。
输入输出示例

代码
class Solution {
public boolean isAnagram(String s, String t) {
char[] s1 = s.toCharArray();
char[] t1 = t.toCharArray();
int[] arr = new int[26];
for(char c : s1){
arr[c - 'a'] += 1;
}
for(char c : t1){
arr[c - 'a'] -= 1;
}
for(int i : arr){
if(i != 0) return false;
}
return true;
}
}边栏推荐
- Quantitative Genetics Heritability Calculation 2: Half Siblings and Full Siblings
- [21天学习挑战赛——内核笔记](四)——内核常见调试手段(printf、dump_stack、devmem)
- 数字化时代,企业为什么需要商业智能BI
- Alibaba Cloud Tianchi Contest Question (Machine Learning) - Prediction of Industrial Steam Volume (Complete Code)
- 亚马逊面对风控,自养号测评时应该怎么做?
- How to do the stability test, this article thoroughly explains it!
- Alibaba Cloud Tianchi Contest Question (Machine Learning) - Repeat Purchase Prediction of Tmall Users (Complete Code)
- 什么是通用微处理器、单片机、DSP芯片、嵌入式系统?
- perl基础语法归纳
- 【Harmony OS】【ARK UI】Date Basic Operation
猜你喜欢

2022年8月深圳产品经理认证招生简章(NPDP)

Cluster deployment using ceph-deploycep with 3 disks as dedicated osd

2022 High-altitude installation, maintenance, and demolition exam practice questions and mock exams

LeetCode-636. 函数的独占时间

I.MX6U-ALPHA开发板(高精度定时器)

【Harmony OS】【ArkUI】ets开发 基础页面布局与数据连接
Improve the user experience and add a small detail to your modal popup

ABP 6.0.0-rc.1的新特性
——内核常见调试手段(printf、dump_stack、devmem)](/img/85/7b65fb095e9cbf724118f98581991a.png)
[21天学习挑战赛——内核笔记](四)——内核常见调试手段(printf、dump_stack、devmem)

LeetCode - remove consecutive nodes with a sum of zero from a linked list
随机推荐
存储系统架构演变
"IP" command to configure network interface
说明高级语言、汇编语言、机器语言三者的区别,谈谈你对汇编语言的认识。
uboot中board_init bi_arch_number在哪
Dingding conflicts with RStudio shortcuts--Dingding shortcut settings
ddr系统检验
JS-DOM-对象的事件onload、匿名函数、this
Faced with risk control, what should Amazon do when evaluating self-supporting accounts?
【学习笔记】AGC044
Improve the user experience and add a small detail to your modal popup
【Harmony OS】【ARK UI】ETS 上下文基本操作
perl基础语法归纳
【luogu U142356】Suffix of the Brave (SA) (Chairman Tree) (2 points)
【Harmony OS】【ARK UI】轻量级数据存储
数字化时代,企业为什么需要商业智能BI
杰理之智能充电仓低电发码关机 触摸不开机【篇】
[Harmony OS] [ArkUI] ets development graphics and animation drawing
Masked AutoEncoder论文及实现
y91.第六章 微服务、服务网格及Envoy实战 -- 服务网格基础(二)
程序设计6大原则