Monday, August 24, 2015

Valid Anagram @Leetcode

Valid Anagram Total Accepted: 16056 Total Submissions: 47146 My Submissions Question Solution
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.

很弱的题。空间和时间的balance.
省空间,用sort.
省时间,用hashtable.

class Solution {
public:
bool isAnagram(string s, string t) {
if (s.size() != t.size()) return false;
unordered_map<char, int> a, b;
for (int i = 0; i<s.size(); i++) {
if (a.count(s[i])) {
a[s[i]]++;
} else {
a[s[i]] = 1;
}
}
for (int i = 0; i<t.size(); i++) {
if (b.count(t[i])) {
b[t[i]]++;
} else {
b[t[i]] = 1;
}
}
return a == b;
}
};
view raw valid anagram hosted with ❤ by GitHub
class Solution {
public:
bool isAnagram(string s, string t) {
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s==t;
}
};
view raw valid anagram hosted with ❤ by GitHub

No comments:

Post a Comment

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...