Blind 75

Valid Anagram

Problem
LC 242
Category
String
File
blind75_LC242ValidAnagram.java
Path
pkg5leetcode/blind75/blind75_LC242ValidAnagram.java
Package
pkg5leetcode.blind75
Command
java pkg5leetcode/blind75/blind75_LC242ValidAnagram.java
Approach
Frequency count arrays for both strings.
Complexity
Time O(n), Space O(26)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/blind75/blind75_LC242ValidAnagram.java
1package pkg5leetcode.blind75;2 3/*4 * Valid Anagram | LC 2425 * APPROACH: Frequency count arrays for both strings.6 * COMPLEXITY: Time O(n), Space O(26)7 */8public class blind75_LC242ValidAnagram {9    static boolean isAnagram(String s, String t) {10        if (s.length() != t.length()) return false;11        int[] cnt = new int[26];12        for (int i = 0; i < s.length(); i++) {13            cnt[s.charAt(i) - 'a']++;14            cnt[t.charAt(i) - 'a']--;15        }16        for (int x : cnt) if (x != 0) return false;17        return true;18    }19 20    public static void main(String[] args) {21        check(isAnagram("anagram", "nagaram"), "case1");22        check(!isAnagram("rat", "car"), "case2");23        System.out.println("all tests passed");24    }25 26    static void check(boolean cond, String name) {27        if (!cond) throw new AssertionError("FAILED: " + name);28        System.out.println("  PASS " + name);29    }30}