import java.util.HashMap;
/**
* Created on 16/6/3.
*/
public class validAnagram {
public static void main(String[] args) {
String a = "anagram";
String b = "nagaram";
boolean x = isAnagram(a, b);
boolean x2 = anotherIsAnagram(a, b);
System.out.println(x);
System.out.println(x2);
}
public static boolean anotherIsAnagram(String a, String b) {
int len1 = a.length();
int len2 = b.length();
if (len1 != len2 || a == null || b == null) {
return false;
}
int[] num = new int[26];
for (int i = 0; i < a.length(); i++) {
num[a.charAt(i) - 'a']++;
num[b.charAt(i) - 'a']--;
}
for (int j = 0; j < a.length(); j++) {
if (num[j] != 0) {
return false;
}
}
return true;
}
public static boolean isAnagram(String a, String b) {
HashMap<Character, Integer> x = new HashMap<>();
for (char c1 : a.toCharArray()) {
if (!x.containsKey(c1)) {
x.put(c1, 1);
} else {
x.put(c1, x.get(c1) + 1);
}
}
for (char c2 : b.toCharArray()) {
if (!x.containsKey(c2)) {
return false;
} else {
x.put(c2, x.get(c2) - 1);
if (x.get(c2) == 0) {
x.remove(c2);
}
}
}
if (x.isEmpty()) {
return true;
} else {
return false;
}
}
}
【Java】validAnagram同字母异序
最新推荐文章于 2024-04-04 18:22:30 发布