【LeetCode刷题记录-----有效的字符异位词】
给定两个字符串 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 仅包含小写字母
代码
#include <stdio.h>
#include <string>
bool isAnagram(char* s, char* t)
{
int lens = strlen(s); //字符串s长度
int lent = strlen(t); //字符串t长度
int arrs[26] = { 0 }; //存储s中的26个小写字母出现的次数
int arrt[26] = { 0 }; //存储t中的26个小写字母出现的次数
bool ans = true;
//获取s中字母出现的次数
for (int i = 0; i < lens; i++)
{
int temp = s[i] - 'a';
arrs[temp]++;
}
//获取t中字母出现的次数
for (int i = 0; i < lent; i++)
{
int temp = t[i] - 'a';
arrt[temp]++;
}
//字母不一致ans置false
for (int i = 0; i < 26; i++)
{
if (arrs[i] != arrt[i])
{
ans = false;
}
}
return ans;
}
int main() {
char s1[] = "rat";
char s2[] = "car";
bool ans = isAnagram(s1,s2);
printf("%d",ans);
return 0;
}
时间复杂度O(n)
测试用例
输入
s = “anagram”
t = “nagaram”
输出
true
输入
s =“rat”
t =“car”
输出
false