当前位置:网站首页>【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;
}
};
边栏推荐
猜你喜欢
Come n times - 07. Rebuild the binary tree
odoo14 | 附件上传功能及实际使用
PyQt5快速开发与实战 9.4 Matplotlib在PyQt中的应用
Canvas particles change various shapes js special effects
js右侧圆点单页滚动介绍页面
Day113. Shangyitong: user authentication, Alibaba Cloud OSS, patient management
Implement a thread pool
VMware下安装win10启动后进入Boot Manger界面如何解决
csdn file export to pdf
Emotional crisis, my friend's online dating girlfriend wants to break up with him, ask me what to do
随机推荐
开放麒麟 openKylin 自动化开发者平台正式发布
【TCP/IP】Network Model
centos7安装mysql5.7
Kotlin入门介绍篇
Come n times with the sword--05. Replace spaces
js空气质量aqi雷达图分析
loadrunner-controller-手动场景Schedule配置
来n遍剑指--07. 重建二叉树
loadrunner-controller-场景执行run
Build finished with errors/Executable Not Found
如何将虚拟机上的文件复制到主机上
Use turtle to draw buttons
湖仓一体电商项目(二):项目使用技术及版本和基础环境准备
解决rpc error: code = Unimplemented desc = method CheckLicense not implemented
The future of the hybrid interface: conversational UI
A Spark SQL online problem troubleshooting and positioning
canvas粒子变幻各种形状js特效
Kotlin—基本语法(一)
Flink1.15 source code reading flink-clients - flink command line help command
Source code analysis of GZIPInputStream class