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.
思路一:将两个String,分别转换为字符型数组。排序。再讲这两个数组转化为字符串。比较这两个字符段是否相等。代码如下
public class Solution {
public boolean isAnagram(String s, String t) {
char[] schar = s.toCharArray();
char[] tchar = t.toCharArray();
Arrays.sort(schar);
Arrays.sort(tchar);
return (String.valueOf(schar)).equals(String.valueOf(tchar));
}
}
思路二:新建数组 a[26], index,实际意义为26个英文字母。针对第一个字符串,若出现一字母,则在其对应index的地方,加一。针对第二个字符段,则减一。最后该数组所有值均为0.
public class Solution {
public boolean isAnagram(String s, String t) {
int[] count = new int[26];
char[] ss = s.toCharArray();
char[] tt = t.toCharArray();
for(int i = 0; i < ss.length; i++){
int k = ss[i] - 'a';
count[k]++;
}
for(int i = 0; i < tt.length; i++){
int k = tt[i] - 'a';
count[k]--;
}
for(int i = 0; i < 26; i++){
if (count[i] != 0)
return false;
}
return true;
}
}