242. Valid Anagram — Easy

前往題目

搬運一下以前的文章,幸好我對於這題的第一想法已經不是用 hashmap 了,有進步!

想法

  • 非常簡單,但一開始用了hashmap,太冗餘了,簡單的array存count就可以了

Code

class Solution {
    public boolean isAnagram(String s, String t) {
        // Base case
        if (s.length() != t.length()) return false;

        // Store alphabetes counts
        int[] count = new int[26];
        
        // Record counts
        for (char c : s.toCharArray()) {
            count[c - 97]++;
        }

        // Check counts
        for (char c : t.toCharArray()) {
            if (count[c - 97] == 0) return false;

            count[c - 97]--;
        }
        
        return true;
    }
}

242. Valid Anagram — Easy
https://f88083.github.io/2025/05/11/242-Valid-Anagram-—-Easy/
作者
Simon Lai
發布於
2025年5月11日
許可協議