LeetCode--ValidAnagram
题目: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. (两个字符串的单词是一样的,只是顺序不一致。)
1、可以利用java的sort函数,将两个单词排序,然后比较;(排序判相等)
public boolean isAangram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
char a[] = s.toCharArray();
char b[] = t.toCharArray();
Arrays.sort(a);
Arrays.sort(b);
for (int i = 0; i < a.length; i++) {
if (a[i] != b[i])
return false;
}
return true;
}
这个题目是考察数组的应用---------另外一种思路:(计数判相等)
public class ValidAnagram {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length())
return false;
int words[] = new int[26];
for (int i = 0; i < s.length(); i++) {
words[s.charAt(i) - 'a']++; // 题目的经典---现在数组中记录字母出现的次数,然后再用t去除这些次数;
// 如果最后可以恢复为0,那么说明两者是anagram的;
words[t.charAt(i) - 'a']--;
}
for (int x : words) {
if (x != 0)
return false;
}
return true;
}
}