LeetCode 1657. Determine if Two Strings Are Close

Post by ailswan May. 17, 2024

1657. Determine if Two Strings Are Close

Problem Statement

link: LeetCode.cn LeetCode Two strings are considered close if you can attain one from the other using the following operations:

Operation 1: Swap any two existing characters. For example, abcde -> aecdb Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character. For example, aacabb -> bbcbaa (all a’s turn into b’s, and all b’s turn into a’s) You can use the operations on either string as many times as necessary.

Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise.

Example:

Input: word1 = "abc", word2 = "bca" Output: true

Input: word1 = "a", word2 = "aa" Output: false

Input: word1 = "cabbba", word2 = "abbccc" Output: true

Solution Approach

To determine if two strings are close, check if they have the same unique characters and if the sorted frequencies of these characters match.

Algorithm

  1. Check Character Sets: Verify that both strings contain the same unique characters by comparing the sets of characters in each string.
  2. Count Character Frequencies: Use a frequency count to determine how many times each character appears in both strings.
  3. Compare Sorted Frequencies: Ensure that the sorted lists of character frequencies are identical for both strings.

Implement

    class Solution: def closeStrings(self, word1: str, word2: str) -> bool:
    count1 = Counter(word1)
    count2 = Counter(word2)

    if set(count1.keys()) != set(count2.keys()):
        return False

    if sorted(count1.values()) != sorted(count2.values()):
        return False
    
    return True 

    //java code
import java.util.HashMap;
import java.util.Map;
class Solution {
    public boolean closeStrings(String word1, String word2) {
        // a   b  swap  change same number.  ct should be same
        // a.  b transform  change diff number . ct key can swap but value are same
        // ct1, ct2 
        // sort ct1.values. ct2.values : (1) char must existed in both strings(2)check equals?
        int[] ct1 = new int[26], ct2 = new int[26];
        for (char c: word1.toCharArray()) {
            ct1[c - 'a']++;
        }
        for (char c: word2.toCharArray()) {
            ct2[c - 'a']++;
        }
        for (int i = 0; i < 26; i++) {
            if (ct1[i] > 0 && ct2[i] == 0 || ct1[i] == 0 && ct2[i] > 0) {
                return false;
            }
        }
        Arrays.sort(ct1);
        Arrays.sort(ct2);
        return Arrays.equals(ct1, ct2);
    }
}