1. 程式人生 > >LintCode日記(一)——兩個字符串是變位詞(C++,Python)

LintCode日記(一)——兩個字符串是變位詞(C++,Python)

函數 ring sort code 日記 解決 str 字符 題目

題目描述:

寫出一個函數 anagram(s, t) 判斷兩個字符串是否可以通過改變字母的順序變成一樣的字符串。

解題思路:

C++:引入哈希的思維,這道題就迎刃而解了。

C++ Code:

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
int dic[58];
for (int i = 0; i < 58; i++)
dic[i] = 0;
for ( int i = 0; i < s.size(); i++ )
{
if (s[i] == ‘ ‘)
continue;
int index = s[i] - ‘A‘;
dic[index]++;
}
for ( int i = 0; i < t.size(); i++ )
{
if (t[i] == ‘ ‘)
continue;
int index = t[i] - ‘A‘;
dic[index]--;
}
for ( int i = 0; i < 58; i++ )
{
if (i==57 && dic[i]==0)
return true;
if (dic[i] == 0)
continue;
else
return false;
}
}
};

Python:利用Python的list()方法與sort()方法就可以成功地解決這道問題。

Python Code:

class Solution:
"""
@param s: The first string
@param b: The second string
@return true or false
"""
def anagram(self, s, t):
# write your code here
a = list(s)
b = list(t)
a.sort()
b.sort()
if a == b:
return True
else:
return False

LintCode日記(一)——兩個字符串是變位詞(C++,Python)