题目
给定两个字符串s和t,请判断它们是不是一组变位词。在一组变位词中,它们中的字符及每个字符出现的次数都相同,但字符的顺序不能相同。例如,"anagram"和"nagaram"就是一组变位词。
分析
如果只考虑英文字母,则用数组模拟哈希表先考虑字符串中只包含英文小写字母的情形。由于英文小写字母只有26个,因此可以用一个数组来模拟哈希表。
解
public class Test {public static void main(String[] args) {boolean anagram = isAnagram("anagram", "nagaram");System.out.println(anagram);}public static boolean isAnagram(String str1, String str2) {if (str1.length() != str2.length()) {return false;}int[] counts = new int[26];for (char ch : str1.toCharArray()) {counts[ch - 'a']++;}for (char ch : str2.toCharArray()) {if (counts[ch - 'a'] == 0) {return false;}counts[ch - 'a']--;}return true;}
}
哈希表方法:
public class Test {public static void main(String[] args) {boolean anagram = isAnagram("anagram", "nagaram");System.out.println(anagram);}public static boolean isAnagram(String str1, String str2) {if (str1.length() != str2.length()) {return false;}Map<Character, Integer> counts = new HashMap<>();for (char ch : str1.toCharArray()) {counts.put(ch, counts.getOrDefault(ch, 0) + 1);}for (char ch : str2.toCharArray()) {if (!counts.containsKey(ch) || counts.get(ch) == 0) {return false;}counts.put(ch, counts.get(ch) - 1);}return true;}
}