LeetCode 75

Determine if Two Strings Have Equal Character Frequency

Problem
LC 1657
Topic
Hash Map / Set
File
official75_LC1657DetermineIfTwoStringsHaveEqualCharacterFrequency.java
Path
pkg5leetcode/official75/official75_LC1657DetermineIfTwoStringsHaveEqualCharacterFrequency.java
Package
pkg5leetcode.official75
Command
java pkg5leetcode/official75/official75_LC1657DetermineIfTwoStringsHaveEqualCharacterFrequency.java
Approach
Same length and same sorted char frequency arrays.
Complexity
Time O(n), Space O(1)

LeetCode solutions

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

pkg5leetcode/official75/official75_LC1657DetermineIfTwoStringsHaveEqualCharacterFrequency.java
1package pkg5leetcode.official75;2 3/*4 * Determine if Two Strings Have Equal Character Frequency | LC 16575 * APPROACH: Same length and same sorted char frequency arrays.6 * COMPLEXITY: Time O(n), Space O(1)7 */8import java.util.*;9 10public class official75_LC1657DetermineIfTwoStringsHaveEqualCharacterFrequency {11    static boolean closeStrings(String word1, String word2) {12        if (word1.length() != word2.length()) return false;13        int[] c1 = new int[26], c2 = new int[26];14        for (int i = 0; i < word1.length(); i++) {15            c1[word1.charAt(i) - 'a']++;16            c2[word2.charAt(i) - 'a']++;17        }18        for (int i = 0; i < 26; i++)19            if ((c1[i] == 0) != (c2[i] == 0)) return false;20        Arrays.sort(c1);21        Arrays.sort(c2);22        return Arrays.equals(c1, c2);23    }24 25    public static void main(String[] args) {26        check(closeStrings("abc", "bca"), "case1");27        check(!closeStrings("a", "aa"), "case2");28        check(closeStrings("cabbba", "abbccc"), "case3");29        System.out.println("all tests passed");30    }31 32    static void check(boolean cond, String name) {33        if (!cond) throw new AssertionError("FAILED: " + name);34        System.out.println("  PASS " + name);35    }36}