【题目】
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
【示例 1】
输入: s = “anagram”, t = “nagaram”
输出: true
【示例 2】
输入: s = “rat”, t = “car”
输出: false
【说明】
你可以假设字符串只包含小写字母。
【进阶】
如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?
【代码】
【Python】
【方法1】
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
s_dict,t_dict={},{}
for c in s:
if c not in s_dict:
s_dict[c]=0
s_dict[c]+=1
for c in t:
if c not in t_dict:
t_dict[c]=0
t_dict[c]+=1
if len(s)!=len(t):
return False
for c in s_dict:
print(c)
if c not in t_dict:
return False
if t_dict[c]!=s_dict[c]:
return False
return True
【方法2】
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s)==sorted(t)
【CPP】
执行用时:
4 ms, 在所有 C++ 提交中击败了98.19%的用户
内存消耗:
7.2 MB, 在所有 C++ 提交中击败了88.66%的用户
class Solution {
public:
bool isAnagram(string s, string t) {
int cnt[26]={0},cnt2[26]={0};
for(auto x:s)
cnt[x-'a']++;
for(auto x:t)
cnt2[x-'a']++;
for(int i=0;i<26;i++)
if(cnt2[i]!=cnt[i])
return false;
return true;
}
};
博客围绕判断两个字符串是否为字母异位词展开,给出示例及说明,假设字符串只含小写字母并提出进阶问题,即输入含unicode字符时解法的调整。同时给出Python和C++代码,展示了C++代码的执行用时和内存消耗情况。
570

被折叠的 条评论
为什么被折叠?



