DEV Community

vc7
vc7

Posted on

1 1 1

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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay