当前位置:网站首页>leetcode:242. 有效的字母异位词
leetcode:242. 有效的字母异位词
2022-06-23 13:02:00 【uncle_ll】
242. 有效的字母异位词
来源:力扣(LeetCode)
链接: https://leetcode.cn/problems/valid-anagram/
给定两个字符串 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 ∗ 1 0 4 5 * 10^4 5∗104
- s 和 t 仅包含小写字母
进阶: 如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?
解法
- 排序:二者排序之后挨个元素进行比较;
- 哈希表:首先判断二者的长度是否相同,如果长度不同的话直接返回false;另外用一个哈希表进行比存储遍历的结构,key是元素,value是元素出现的次数;之后再遍历另一个字符串,如果元素在哈希表中,将次数减1,如果减到负数,直接返回false,如果不在哈希表中,也直接返回false;遍历到最后,看一下哈希表中每个key对应的次数是否为0;
代码实现
排序
使用列表自带的性质;
python实现
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t)
c++实现
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.size() != t.size())
return false;
sort(s.begin(), s.end());
sort(t.begin(), t.end());
for (int i=0; i<s.size(); i++) {
if (s[i] != t[i])
return false;
}
return true;
}
};
复杂度分析
- 时间复杂度: O ( N l o g N ) O(NlogN) O(NlogN)
- 空间复杂度: O ( l o g N ) O(logN) O(logN) 排序需要空间
哈希表
python实现
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
counts = dict()
for ch in s:
if ch in counts:
counts[ch] += 1
else:
counts[ch] = 1
for ch in t:
if ch in counts:
counts[ch] -= 1
if counts[ch] == 0:
del counts[ch] # 删掉次数为0的key
else:
return False
return len(counts) == 0
c++实现
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.size() != t.size())
return false;
unordered_map<char, int> counts;
for(char ch: s) {
auto it = counts.find(ch);
if (it != counts.end())
counts[ch]++;
else
counts[ch] = 1;
}
for (char ch: t) {
auto it = counts.find(ch);
if (it == counts.end())
return false;
counts[ch]--;
if (counts[ch] == 0)
counts.erase(ch);
}
return counts.size() == 0;
}
};
复杂度分析
- 时间复杂度: O ( N ) O(N) O(N)
- 空间复杂度: O ( S ) O(S) O(S) 字符的个数
边栏推荐
- Can cold plate, submerged and spray liquid cooling lead the development of high-performance computing?
- quartus调用&设计D触发器——仿真&时序波验证
- 你管这破玩意儿叫 MQ?
- TUIKit 音视频低代码解决方案导航页
- AAIG看全球6月刊(上)发布|AI人格真的觉醒了吗?NLP哪个细分方向最具社会价值?Get新观点新启发~
- 交换两个数的三种方法原理解析
- The R language inputs the distance matrix to the hclust function for hierarchical clustering analysis, uses the cutree function to divide the hierarchical clustering clusters, specifies the number of
- 5 technical vulnerabilities related to NFT
- 构建英特尔 DevCloud
- 使用OpenVINOTM预处理API进一步提升YOLOv5推理性能
猜你喜欢

What is the principle of live CDN in the process of building the source code of live streaming apps with goods?

The two 985 universities share the same president! School: true

构建英特尔 DevCloud

618的省钱技术攻略 来啦 -体验场景 领取10元猫超卡!

Yyds dry inventory solution sword finger offer: judge whether it is a balanced binary tree

64 channel telephone +2-channel Gigabit Ethernet 64 channel PCM telephone optical transceiver voice telephone to optical fiber

Go写文件的权限 WriteFile(filename, data, 0644)?

quartus調用&設計D觸發器——仿真&時序波驗證

华三交换机配置SSH远程登录

Can cold plate, submerged and spray liquid cooling lead the development of high-performance computing?
随机推荐
C语言的基本数据类型及其打印输出
互联网技术发展内卷后的出路——iVX的诞生
Loss, duplication and backlog of message queues
618's money saving technology strategy is coming - experience the scene and get a 10 yuan cat super card!
AGCO AI frontier promotion (6.23)
怎么手写vite插件
Detailed description of Modelsim installation steps
CRMEB 二开短信功能教程
Scope of groovy
【课程预告】基于飞桨和OpenVINO 的AI表计产业解决方案 | 工业读表与字符检测
Quartus call & Design d Trigger - simulation & time sequence Wave Verification
quartus调用&设计D触发器——仿真&时序波验证
Go写文件的权限 WriteFile(filename, data, 0644)?
In flinksql, the Kafka flow table and MySQL latitude flow table are left joined, and the association is made according to I'd. false
How did Tencent's technology bulls complete the overall cloud launch?
.Net怎么使用日志框架NLog
使用OpenVINOTM预处理API进一步提升YOLOv5推理性能
R language uses the multinom function of NNET package to build a disordered multi classification logistic regression model, uses regression coefficients and their standard errors to calculate the valu
How to use sed -i command
Esp32-c3 introductory tutorial problem ⑦ - fatal error: ESP_ Bt.h: no such file or directory ESP not found_ bt.h