1657. Determine if Two Strings Are Close
技術標籤:LeetCode
題目:
Two strings are consideredcloseif you can attain one from the other using the following operations:
- Operation 1: Swap any twoexistingcharacters.
- For example,
abcde-> aecdb
- For example,
- Operation 2: Transformeveryoccurrence of oneexistingcharacter into anotherexistingcharacter, and do the same with the other character.
- For example,
aa
(alla
's turn intob
's, and allb
's turn intoa
's)
- For example,
You can use the operations on either string as many times as necessary.
Given two strings,word1
andword2
, returntrue
ifword1
andword2
areclose, andfalse
otherwise.
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"
Example 4:
Input: word1 = "cabbba", word2 = "aabbss" Output: false Explanation: It is impossible to attain word2 from word1, or vice versa, in any amount of operations.
Constraints:
1 <= word1.length, word2.length <= 10^5
word1
andword2
containonly lowercase English letters.
思路:
這道題看上去有點花裡胡哨,但是大概是Contest第二題的樣子,所有理論上不會太難。讀完題目我們可以用三個條件來制約給定的兩個陣列,以此判斷他們是否close。首先長度肯定要一樣;其次因為我們關心的是字元以及字元出現的次數,順序無關緊要,所以我們可以sort。對於出現的字元,我們set來記錄;而字元出現的次數,因為是一個一直要改變的key(每次出現已出現字元,次數需要加一),因此用set就不太合適,但是如果用hash map,在比較的時候又不好sort(我們只需要sort次數,而對應次數是什麼字元我們並不在意),同時考慮到總共也就只有26個字母,可以直接用vector來記錄頻次,只要用當前字元減去'a'就是當前字元在vector中的index--有一點點像簡易版hashmap。最後只要保證sort完的兩個vector和set都相同即可。
程式碼:
class Solution {
public:
bool closeStrings(string word1, string word2) {
int len1=word1.size();
int len2=word2.size();
if(len1!=len2)
return 0;
set<char> s1, s2;
vector<int> fre1(26), fre2(26);
for(auto c:word1)
{
s1.insert(c);
fre1[c-'a']++;
}
for(auto c:word2)
{
s2.insert(c);
fre2[c-'a']++;
}
sort(fre1.begin(),fre1.end());
sort(fre2.begin(),fre2.end());
return s1==s2&&fre1==fre2;
}
};