This is my LeetCode exercise.
You can see all question I did here.
leetcode
medium
Hash Table
String
Sorting
Two strings are considered close if you can attain one from the other using the following operations:
abcde -> aecdb
aacabb -> bbcbaa
(all a
’s turn into b
’s, and all b
’s turn into a
’s)Given two strings, word1
and word2
, return true
if word1
and word2
are close, and false
otherwise.
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”
Input: word1 = “a”, word2 = “aa”
Output: false
Explanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations.
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”
word1
and word2
contain only lowercase English letters.#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;
}
Space | Time |
---|---|
$O(1)$ | $O(Nlog(N))$ |
void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*))
<stdlib.h>
, sort for assign series.*base
: The pointer to the series be sorted.nitems
: How many elements need to be sorted.size
: The size of each element in the series.*compar
: The pointer of function for comparing during sorting.