Problem:
Solution:
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.empty() && t.empty())
return true;
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;
}
};
Another one:
======= Another one =====
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.size() != t.size()) {
return false;
}
unordered_map<char, int> mp;
for (auto ch: s) {
mp[ch]++;
}
for (auto ch: t) {
if (!mp.count(ch)) {
return false;
}
mp[ch]--;
if (mp[ch] < 0) {
return false;
}
}
return true;
}
};
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.
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
Note:
You may assume the string contains only lowercase alphabets.
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?
What if the inputs contain unicode characters? How would you adapt your solution to such case?
Solution:
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.empty() && t.empty())
return true;
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;
}
};
Another one:
- class Solution {
- public:
- bool isAnagram(string s, string t) {
- int len1 = s.length();
- int len2 = t.length();
- if(len1!=len2){
- return false;
- }
- vector<int> count(26, 0);
- for(int i=0; i<len1; i++){
- count[s[i]-'a']++;
- }
- for(int i=0; i<len2; i++){
- if(--count[t[i]-'a']<0){
- return false;
- }
- }
- return true;
- }
- };
======= Another one =====
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.size() != t.size()) {
return false;
}
unordered_map<char, int> mp;
for (auto ch: s) {
mp[ch]++;
}
for (auto ch: t) {
if (!mp.count(ch)) {
return false;
}
mp[ch]--;
if (mp[ch] < 0) {
return false;
}
}
return true;
}
};
No comments:
Post a Comment