一. 题目:Valid Anagram
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return 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?
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return 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?
Subscribe to see which companies asked this question.
二. 思路分析
首先先判断两个字符串的长度是否一样,若不一样则返回false;定义一个包含26个整数的数组Num,用于保存每个字母出现的次数,遍历字符串s,将每个字母出现的次数记录在数组Num里;再次遍历字符串t,若该字母对应的位置存储的值为0,则代表该字母为s没出现过或s出现过,但是已经被t之前的字母抵消,即该字母在s中无法找到想匹配的字母,返回false;若对应位置存储的值不为0,则值自减1,表示s中的该字母被抵消了一个。代码如下:
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.size() != t.size()){
return false;
}
int nums[26]={0};
for(int i = 0; i < s.size(); i++){
nums[s[i] - 'a']++;
}
for(int i = 0; i < t.size(); i++){
if(nums[t[i] - 'a'] == 0){
return false;
} else{
nums[t[i] - 'a']--;
}
}
return true;
}
};
Follow out
What if the inputs contain unicode characters? How would you adapt your solution to such case?
使用哈希表实现,在c++中可以用stl中的map实现。若按照上面的方法为unicode的每个字符都开辟一个数组元素,则该数组将会非常之大。