public class Solution {
public boolean isAnagram(String s, String t) {
if (s == null || t == null || s.length() != t.length()) {
return false;
}
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i <= s.length() - 1; i++) {
String subs = s.substring(i, i + 1);
String subt = t.substring(i, i + 1);
if (map.containsKey(subs)) {
map.put(subs, map.get(subs) + 1);
} else {
map.put(subs, 1);
}
if (map.containsKey(subt)) {
map.put(subt, map.get(subt) - 1);
} else {
map.put(subt, -1);
}
}
for (Map.Entry<String, Integer> entry: map.entrySet()) {
if (entry.getValue() != 0) {
return false;
}
}
// for (int count: map.values()) {
// if (count != 0) {
// return false;
// }
// }
return true;
// if (s == null || t == null || s.length() != t.length()) {
// return false;
// }
// int[] array = new int[26];
// for (int i = 0; i < s.length(); i++) {
// array[s.charAt(i) - 'a'] = array[s.charAt(i) - 'a'] + 1;
// array[t.charAt(i) - 'a'] = array[t.charAt(i) - 'a'] - 1;
// }
// for (int n: array) {
// if (n != 0) {
// return false;
// }
// }
// return true;
// Map<Character, Integer> map = new HashMap<>();
// char[] sArray = s.toCharArray();
// char[] tArray = t.toCharArray();
// for (char c: sArray) {
// if (map.containsKey(c)) {
// map.put(c, map.get(c) + 1);
// } else {
// map.put(c, 1);
// }
// }
// for (char c: tArray) {
// if (map.containsKey(c)) {
// map.put(c, map.get(c) - 1);
// } else {
// return false;
// }
// }
// for (Map.Entry<Character, Integer> entry: map.entrySet()) {
// if (entry.getValue() != 0) {
// return false;
// }
// }
// return true;
}
}
Valid Anagram
最新推荐文章于 2024-01-10 12:44:07 发布