题目描述:
Write a method anagram(s,t) to decide if two strings are anagrams or not.
What is Anagram?
- Two strings are anagram if they can be the same after change the order of characters.
Given s = "abcd", t = "dcab", return true.
Given s = "ab", t = "ab", return true.
Given s = "ab", t = "ac", return false.
O(n) time, O(1) extra space
题目要求O(n) time, O(1) space,如果直接用map或者直接循环match两次,都是不可行的。这里发现,虽然string长度是无限的,可是用来表示characters的ASCII码是有限的嘛!这里可以建一个256 size的vector,将s中出现的ch按照次数填入vector中,而ch的index就是它对应的ASCII码的int。再看t中的每一个ch有没有一一对应即可。
Mycode (AC = 18ms):
class Solution {
public:
/**
* @param s: The first string
* @param b: The second string
* @return true or false
*/
bool anagram(string s, string t) {
// write your code here
vector<int> chmap(256, 0);
// if length not equal, then return false
if (s.length() != t.length()) {
return false;
}
// put s info into chmap
for (int i = 0; i < s.length(); i++) {
int intch = (int)(s[i]);
chmap[intch] += 1;
}
// put t info into chmap
for (int j = 0; j < t.length(); j++) {
int intch = (int)(t[j]);
chmap[intch] -= 1;
if (chmap[intch] < 0) {
return false;
}
}
return true;
}
};
本文介绍了一种高效判断两个字符串是否为异构词的方法,通过使用固定大小的字符映射表实现O(n)时间复杂度与O(1)空间复杂度的要求。
2229

被折叠的 条评论
为什么被折叠?



