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>
This commit is contained in:
Alexander Pantyukhin 2023-01-21 03:46:02 +04:00 committed by GitHub
parent 73913ac4a8
commit b98296e02f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 52 additions and 0 deletions

View File

@ -114,6 +114,7 @@
| 1189 | [Maximum Number of Balloons](https://leetcode.com/problems/maximum-number-of-balloons/) | [C](./src/1189.c) | Easy |
| 1207 | [Unique Number of Occurrences](https://leetcode.com/problems/unique-number-of-occurrences/) | [C](./src/1207.c) | Easy |
| 1283 | [Find the Smallest Divisor Given a Threshold]https://leetcode.com/problems/find-the-smallest-divisor-given-a-threshold/description/) | [C](./src/1283.c) | Medium |
| 1657 | [Determine if Two Strings Are Close](https://leetcode.com/problems/determine-if-two-strings-are-close/description/) | [C](./src/1657.c) | Medium |
| 1695 | [Maximum Erasure Value](https://leetcode.com/problems/maximum-erasure-value/) | [C](./src/1695.c) | Medium |
| 1769 | [Minimum Number of Operations to Move All Balls to Each Box](https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/) | [C](./src/1769.c) | Medium |
| 1524 | [Number of Sub-arrays With Odd Sum](https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum/) | [C](./src/1524.c) | Medium |

51
leetcode/src/1657.c Normal file
View File

@ -0,0 +1,51 @@
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;
}