LeetCode 1657: Determine if Two Strings Are Close

Problem Description

Explanation

To determine if two strings are close, we need to check if both strings can be transformed into each other by performing the given operations. We can achieve this by counting the frequency of characters in both strings and comparing these counts. If the frequency counts match for both strings, then the strings are close.

  1. Count the frequency of characters in both strings.
  2. Compare the frequency counts to check if the strings are close.

Time Complexity: O(n), where n is the length of the input strings. Space Complexity: O(1) since we are using a fixed-size array to store character frequencies.

Solutions

class Solution {
    public boolean closeStrings(String word1, String word2) {
        if (word1.length() != word2.length()) {
            return false;
        }

        int[] freq1 = new int[26];
        int[] freq2 = new int[26];
        for (char c : word1.toCharArray()) {
            freq1[c - 'a']++;
        }
        for (char c : word2.toCharArray()) {
            freq2[c - 'a']++;
        }

        for (int i = 0; i < 26; i++) {
            if ((freq1[i] == 0 && freq2[i] != 0) || (freq1[i] != 0 && freq2[i] == 0)) {
                return false;
            }
        }

        Arrays.sort(freq1);
        Arrays.sort(freq2);

        return Arrays.equals(freq1, freq2);
    }
}

Loading editor...