LeetCode Exercise

Logo

This is my LeetCode exercise.
You can see all question I did here.

View the Project on GitHub YaoyuanHsu/LeetCode_Exercise

tags: leetcode medium Hash Table String Sorting

1657. Determine if Two Strings Are Close

Description

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

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

Examples

Example 1:

Input: word1 = “abc”, word2 = “bca”
Output: true
Explanation: You can attain word2 from word1 in 2 operations.
Apply Operation 1: “abc” -> “acb”
Apply Operation 1: “acb” -> “bca”

Example 2:

Input: word1 = “a”, word2 = “aa”
Output: false
Explanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations.

Example 3:

Input: word1 = “cabbba”, word2 = “abbccc”
Output: true
Explanation: You can attain word2 from word1 in 3 operations.
Apply Operation 1: “cabbba” -> “caabbb”
Apply Operation 2: “caabbb” -> “baaccc”
Apply Operation 2: “baaccc” -> “abbccc”

Constraints:

Code

#define ALP_SIZE 26

// Compare function
int compFunc(const void * a, const void * b){
    return *(int *)b - *(int *)a;
}

bool closeStrings(char * word1, char * word2){
    // Compare length of words
    int length = strlen(word1);
    if(length != strlen(word2))
        return false;
    // alph for counting number of each alphabet
    // check for collecting basis set of words
    int check1[ALP_SIZE] = {0}, check2[ALP_SIZE] = {0};
    int alph1[ALP_SIZE] = {0}, alph2[ALP_SIZE] = {0};

    // set check & count alph
    for(int i = 0 ; i < length ; i++){
        check1[word1[i] - 'a'] = 1;
        alph1[word1[i] - 'a']++;
    }
    for(int i = 0 ; i < length ; i++){
        check2[word2[i] - 'a'] = 1;
        alph2[word2[i] - 'a']++;
    }

    // check difference of basis
    for(int i = 0; i < ALP_SIZE; i++){
        if(check1[i] != check2[i])
            return false;
    }

    // sort & check the alphs
    qsort(alph1, ALP_SIZE, sizeof(int), compFunc);
    qsort(alph2, ALP_SIZE, sizeof(int), compFunc);
    for(int i = 0; i < ALP_SIZE; i++) { 
        if(alph1[i] != alph2[i])
            return false;
    }

    return true;
}

Complexity

Space Time
$O(1)$ $O(Nlog(N))$

Result

Notes