当前位置:网站首页>【LeetCode】242. 有效的字母异位词
【LeetCode】242. 有效的字母异位词
2022-07-31 10:03:00 【酥酥~】
题目
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
注意:若 s 和 t 中每个字符出现的次数都相同,则称 s 和 t 互为字母异位词。
示例 1:
输入: s = “anagram”, t = “nagaram”
输出: true
示例 2:
输入: s = “rat”, t = “car”
输出: false
提示:
1 <= s.length, t.length <= 5 * 104
s 和 t 仅包含小写字母
进阶: 如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?
题解
长度不等则直接退出
使用哈希表存储第一个字符串的字符频率
然后对第二个字符串遍历对频率做–运算,遇到-1则为否
class Solution {
public:
bool isAnagram(string s, string t) {
int len1 = s.length();
int len2 = t.length();
if(len1!=len2)
return false;
unordered_map<char,int> mystr;
for(int i=0;i<len1;i++)
{
mystr[s[i]]++;
}
for(int i=0;i<len2;i++)
{
mystr[t[i]]--;
if(mystr[t[i]]<0)
return false;
}
return true;
}
};
使用排序方法,将字符串排序后进行逐个比较
遇到不相同则为否
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.length() != t.length())
return false;
sort(s.begin(),s.end());
sort(t.begin(),t.end());
return s==t;
}
};
边栏推荐
- 小程序如何使用订阅消息(PHP代码+小程序js代码)
- js空气质量aqi雷达图分析
- (C语言)程序环境和预处理
- Come n times - 09. Implement queues with two stacks
- js department budget and expenditure radar chart
- Meikle Studio--Hongmeng 14-day development training notes (8)
- csdn file export to pdf
- Kotlin—基本语法(一)
- Mysql+Navicat for Mysql
- What is the encoding that starts with ?
猜你喜欢
随机推荐
ARC在编译和运行做了什么?
js滚动条滚动到指定元素
Redis的简单使用
恋爱期间的赠与能否撤销
自定义v-drag指令(横向拖拽滚动)
What is the encoding that starts with ?
NowCoderTOP23-27二叉树遍历——持续更新ing
初识二叉搜索树
Build finished with errors/Executable Not Found
Rich text editor Tinymce
来n遍剑指--06. 从尾到头打印链表
Come n times with the sword--05. Replace spaces
NowCoderTOP28-34二叉树——持续更新ing
Dart Log tool class
Build finished with errors/Executable Not Found
让动画每次重复前都有延迟
Redis Sentinel原理
Add a shuffling effect to every pie
开放麒麟 openKylin 自动化开发者平台正式发布
Meikle Studio--Hongmeng 14-day development training notes (8)