当前位置:网站首页>力扣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;
}
}
边栏推荐
- Harmony OS ets ArkUI 】 【 】 the development basic page layout and data connection
- Docker部署MySQL
- leetcode:316. 去除重复字母
- 抖音直播新号怎么起号?抖音直播间不进人怎么办?
- 浅谈产品降本设计
- 【Harmony OS】【ARK UI】Public Event Module
- [Developers must see] [push kit] Collection of typical problems of push service service 2
- 【luogu U142356】勇者的后缀(SA)(主席树)(二分)
- Quantitative Genetics Heritability Calculation 2: Half Siblings and Full Siblings
- 学习笔记--文件夹处理--代码学习
猜你喜欢
随机推荐
算法---优美的排列(Kotlin)
2022下半年深圳信息系统项目管理师认证招生简章
【Harmony OS】【ArkUI】ets开发 基础页面布局与数据连接
【Harmony OS】【ARK UI】轻量级数据存储
OKR management process, how to implement effective dialogue, using the CFR feedback and recognition?
Dingding conflicts with RStudio shortcuts--Dingding shortcut settings
区别如下概念:路径、绝对路径、相对路径、当前目录。系统磁盘上存在某个可执行文件,但在DOS环境输入其文件名却提示没有这个文件,是什么原因?
MySQL: Implementation Principles of Submitted Read and Repeatable Read | MVCC (Multi-Version Concurrency Control) - Notes for Your Own Use
perl基础语法归纳
Golang入门教程
软件测试的发展趋势
php write online remote file to temp file
LeetCode-636. 函数的独占时间
JS-全局dom对象的使用---使用htm样式和js函数动作的完全分离
必须指定GDAL API版本。提供一个路径使用GDAL_CONFIG gdal-config环境
The influence law of genes for disease - read the paper
Quantitative Genetics Heritability Calculation 2: Half Siblings and Full Siblings
Harmony OS ets ArkUI 】 【 】 development create a view and building layout
"IP" command to configure network interface
杰理之一拖二 另一台手机超距 通话会无声【篇】