Files
C/leetcode/src/1657.c
Alexander Pantyukhin b98296e02f feat: add Determine if Two Strings Are Close (#1192)
* add leetcode Determine if Two Strings Are Close

* Update 1657.c

add comments

* Update leetcode/src/1657.c

Co-authored-by: David Leal <halfpacho@gmail.com>
2023-01-20 17:46:02 -06:00

52 lines
1.4 KiB
C

const charLength = 26;
int* charsCount(char* word){
int* result = calloc(charLength, sizeof(int));
int wordLen = strlen(word);
for (int i = 0; i < wordLen; i++){
result[word[i] - 'a']++;
}
return result;
}
int diff(const int *i, const int *j)
{
return *i - *j;
}
// Counting
// Runtime: O(n)
// Space: O(1)
bool closeStrings(char * word1, char * word2){
int* word1CharsCounter = charsCount(word1);
int* word2CharsCounter = charsCount(word2);
// The lengths of both string should be equal
if (strlen(word1) != strlen(word2)){
return false;
}
// The char should appear in both strings
for (int i = 0; i < charLength; i++){
if ((word1CharsCounter[i] != 0 && word2CharsCounter[i] == 0) ||
(word1CharsCounter[i] == 0 && word2CharsCounter[i] != 0)){
return false;
}
}
qsort(word1CharsCounter, charLength, sizeof (int), (int(*) (const void *, const void *)) diff);
qsort(word2CharsCounter, charLength, sizeof (int), (int(*) (const void *, const void *)) diff);
// appearing of chars should be the same in both strings.
for (int i = 0; i < charLength; i++){
if (word1CharsCounter[i] != word2CharsCounter[i]){
return false;
}
}
free(word1CharsCounter);
free(word2CharsCounter);
return true;
}