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.
?
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”
From: LeetCode
Link: 1657. Determine if Two Strings Are Close
Based on the problem statement, we can deduce a few key points to determine if two strings are close:
int compare(const void* a, const void* b) {
return (*(int*)a - *(int*)b);
}
bool closeStrings(char* word1, char* word2) {
if (strlen(word1) != strlen(word2)) return false;
int count1[26] = {0}, count2[26] = {0};
bool exist1[26] = {false}, exist2[26] = {false};
// Count the frequency of each character in both strings
// and mark the existence of characters.
for (int i = 0; word1[i] != '\0'; i++) {
count1[word1[i] - 'a']++;
exist1[word1[i] - 'a'] = true;
count2[word2[i] - 'a']++;
exist2[word2[i] - 'a'] = true;
}
// Check if both strings have the same set of characters.
for (int i = 0; i < 26; i++) {
if (exist1[i] != exist2[i]) return false;
}
// Sort the frequency arrays to compare frequencies.
qsort(count1, 26, sizeof(int), compare);
qsort(count2, 26, sizeof(int), compare);
// Compare the sorted frequency arrays.
for (int i = 0; i < 26; i++) {
if (count1[i] != count2[i]) return false;
}
return true;
}