描述
写出一个函数 anagram(s, t)
判断两个字符串是否可以通过改变字母的顺序变成一样的字符串。
您在真实的面试中是否遇到过这个题?
是
说明
What is Anagram?
- Two strings are anagram if they can be the same after change the order of characters.
样例
给出 s = "abcd"
,t="dcab"
,返回 true
.
给出 s = "ab"
, t = "ab"
, 返回 true
.
给出 s = "ab"
, t = "ac"
, 返回 false
.
挑战
O(n) time, O(1) extra space
使用散列表可以满足挑战要求。
class Solution {
public:
/**
* @param s: The first string
* @param t: The second string
* @return: true or false
*/
bool anagram(string &s, string &t) {
// write your code here
int len_s = s.length(), len_t = t.length(), i, ns[26] = {0};
for(i = 0; i < len_s; i++)
if(s[i]>='a'&&'z'>=s[i])
ns[s[i] - 'a']++;
for(i = 0; i < len_t; i++)
if(t[i]>='a'&&'z'>=t[i])
ns[t[i] - 'a']--;
for(i = 0; i < 26; i++)
if(ns[i] != 0)
return false;
return true;
}
};