首页 > 其他分享 >LeetCode: 242. Valid Anagram

LeetCode: 242. Valid Anagram

时间:2022-12-05 18:03:31浏览次数:45  
标签:26 ch string ++ anagram Valid Anagram alphaOfT LeetCode


LeetCode: 242. Valid Anagram

题目描述

Given two strings ​​s​​​ and ​​t​​​ , write a function to determine if t is an anagram of ​​s​​.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

Note:

  • You may assume the string contains only lowercase alphabets.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

Tips:
An anagram is a word or phrase formed by changing the order of the letters in another word or phrase. For example, “triangle” is an anagram of “integral.”

解题思路

将 ​​a-z​​​ 映射到 ​​0-25​​,用数组统计各单词中各字母出现的次数是否相等。若出现次数相等,则是 Anagram。否则,不是。

AC 代码

class Solution {
public:
bool isAnagram(string s, string t) {
int alphaOfS[26] = {0};
int alphaOfT[26] = {0};

for(char ch : s) ++alphaOfS[ch-'a'];
for(char ch : t) ++alphaOfT[ch-'a'];

bool ans = true;
for(int i = 0; i < 26; ++i)
{
if(alphaOfS[i] != alphaOfT[i])
{
ans = false;
break;
}
}

return ans;
}
};


标签:26,ch,string,++,anagram,Valid,Anagram,alphaOfT,LeetCode
From: https://blog.51cto.com/u_15903085/5913210

相关文章