DEV Community

vc7
vc7

Posted on

242. Valid Anagram - Java 練習 - HashMap (中文解釋)

題目

題意

Anagram 的意思是「相同字母異序詞」(維基)。

題目會提供兩個字串,需要判斷這兩個字串是不是 anagram 。

解法

這篇先用自己直觀想到的想法解。


想法

因為只需要考慮出現次數而不需要考慮次數,因此可以用 Hash Map 來記數。 Key 為字元, value 為次數。

流程

  1. 第一想法是,各自計算出各自的 hash map 再比較
  2. 先統計第一個字串的 hash map 再用第二個字串腳去第一個字串的. hash map
    • 如果剩餘的 hash map 有非零,就代表兩個字串不一樣

程式碼

class Solution { // Function is to check whether two strings are anagram of each other or not. public static boolean areAnagrams(String s1, String s2) { Map<Character, Integer> map = new HashMap<>(); for (Character x : s1.toCharArray()) { map.put(x, map.getOrDefault(x, 0) + 1); } for (Character x: s2.toCharArray()) { map.put(x, map.getOrDefault(x, 0) - 1); } for (Integer count: map.values()) { if (count != 0) { return false; } } return true; } } 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)