哈希思想
利用哈希表分别统计两个字符串中出现的字母次数,如果满足条件则哈希表中两串的字母出现次数是相同的。
class Solution {
public boolean isAnagram(String s, String t) {
if(s.length() != t.length()) return false;
int[] st = new int[(char)‘z‘+1];
int[] tt = new int[(char)‘z‘+1];
for(int i = 0; i < s.length(); i++) {
st[s.charAt(i)]++;
tt[t.charAt(i)]++;
}
for(int i = (char)‘a‘; i < (char)‘z‘+1; i++) {
if(st[i] != tt[i]) return false;
}
return true;
}
}
排序法
有很多问题都能通过使数据变得有序解决。
class Solution {
public boolean isAnagram(String s, String t) {
char[] a = s.toCharArray();
char[] b = t.toCharArray();
Arrays.sort(a);
Arrays.sort(b);
return Arrays.equals(a, b) ? true : false;
}
}
原文:https://www.cnblogs.com/fromneptune/p/13246262.html