刷题第3天,题目链接:https://leetcode.com/problems/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?
两种思路,第一种方法将数组排序以后,再比较,如果相同就返回true,否则返回false。第二种方法,建立一个map统计两个字符串中每个字母出现的次数,s中每出现一个字母就将对应键的值++,t中每出现一个字母就将对应键的值--。最后统计map中所有元素的键值,一旦发现有值不为0的就返回false,否则返回true。
方法一:
bool isAnagram(string s, string t) {
sort(s.begin(),s.end());
sort(t.begin(),t.end());
if(s.compare(t)==0)return true;
else return false;
}
方法二:
bool isAnagram(string s, string t) {
map<char,int> m;
if(s.length()!=t.length())return false;
for(int i=0;i<s.length();i++){
m[s[i]]++;
m[t[i]]--;
}
for(map<char,int>::iterator it=m.begin();it!=m.end();it++){
if((*it).second!=0)return false;
}
return true;
}
在网上看到了一种与方法二类似的解法,只不过使用数组模拟的,更加巧妙,比map更节省空间,所以也把解法搬运了过来:
方法三:
vector<int> count(26, 0);
for(int i = 0; i < s.size(); i ++)
count[s[i]-'a'] ++;
for(int i = 0; i < t.size(); i ++)
count[t[i]-'a'] --;
for(int i = 0; i < 26; i ++)
if(count[i] != 0)
return false;
return true;
}
每天一道题,保持新鲜感,就这样~