Loading

LeetCode problem#242

Valid Anagram

Solved in 1 languageJava

Solve it on LeetCode(opens in a new tab)

Solution

22 lines
1class Solution {
2    public boolean isAnagram(String s, String t) {
3        if (s.length() != t.length()) {
4            return false;
5        }
6
7        int[] counts = new int[26];
8
9        for (int i = 0; i < s.length(); i++) {
10            counts[s.charAt(i) - 'a']++;
11            counts[t.charAt(i) - 'a']--;
12        }
13
14        for (int i = 0; i < counts.length; i++) {
15            if (counts[i] != 0) {
16                return false;
17            }
18        }
19
20        return true;
21    }
22}

Want a walkthrough of this Java solution?

Get a step-by-step explanation of the idea behind the code.

All problems

Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.