两个字符串是变位词
题目
写出一个函数 anagram(s, t) 判断两个字符串是否可以通过改变字母的顺序变成一样的字符串。
样例
给出 s = “abcd”,t=”dcab”,返回 true.
给出 s = “ab”, t = “ab”, 返回 true.
给出 s = “ab”, t = “ac”, 返回 false.题解
本题中字符串由大小写字母构成,则构建一个长度为52的数组。然后在遍历第一个字符串时计算出每个字母的个数,在遍历第二个字符串时在数组中依次减去所含的字符的个数。如果两个字符串是变位词,则数组元素应全部为0,时间复杂度为O(n)。
public class Solution {
/**
* @param s: The first string
* @param b: The second string
* @return true or false
*/
public boolean anagram(String s, String t) {
int[] arr = new int[52];
for (int i=0;i<s.length();i++)
{
if (s.charAt(i) >= 'a' && s.charAt(i) <= 'z')
{
arr[s.charAt(i)-'a']++;
}
else if (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z')
{
arr[s.charAt(i)-'A' + 26]++;
}
}
for (int j=0;j<t.length();j++)
{
if (t.charAt(j) >= 'a' && t.charAt(j) <= 'z')
{
arr[t.charAt(j)-'a']--;
}
else if (t.charAt(j) >= 'A' && t.charAt(j) <= 'Z')
{
arr[t.charAt(j)-'A' + 26]--;
}
}
for (int k=0;k<arr.length;k++)
{
if (arr[k] != 0)
{
return false;
}
}
return true;
}
};
Last Update 2016.9.7