Re: [閒聊] 每日LeetCode已回收
1657. Determine if Two Strings Are Close
給你兩個字串s1和s2判斷他們是不是"close",若字串s1可以透過下列兩種操作轉為s2則
他們為"close",返回true,否則false。
1.交換s1的任意字元位置,例如: aab -> aba
2.將s1的某一種字元和另一個s1中的字元全部替換
例如: aac -> caa(全部a變c且c變a)
Example:
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"
思路:
1.如果s1和s2長度不一樣一定不是close,例如:a aa
2.如果s1有s2沒有的字元或s2沒有s1有的字元他們一定不是close,例如:aab cdd
3.因為我們可以交換字元的任意位置,所以我們只需要關注s1和s2的字元數量即可,
先統計s1和s2的每個單字之數量。
4.因為操作2的關係我們可以交換字元的數量,例如:aaabb -> bbaaa
所以我們將字元的數量排序並檢查s1和s2的數量是否可以兩兩對應,這樣任意字元
都可以透過操作2獲得(因為2的檢查,s1有的字元s2都會有反之亦然)。
cabbba = {2, 3, 1} => {1, 2, 3}
abbccc = {1, 2, 3} => {1, 2, 3}
JavaCode:
----------------------------------------------
class Solution {
public boolean closeStrings(String word1, String word2) {
if (word1.length() != word2.length()) {
return false;
}
int[] count1 = new int[26];
int[] count2 = new int[26];
for (int i = 0; i < word1.length(); i++) {
count1[word1.charAt(i) - 'a']++;
count2[word2.charAt(i) - 'a']++;
}
for (int i = 0; i < 26; i++) {
if (count1[i] == 0 && count2[i] > 0) {
return false;
}
if (count2[i] == 0 && count1[i] > 0) {
return false;
}
}
Arrays.sort(count1);
Arrays.sort(count2);
for (int i = 0; i < 26; i++) {
if (count1[i] != count2[i]) {
return false;
}
}
return true;
}
}
----------------------------------------------
--
https://i.imgur.com/uiFto42.jpg

--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.100.75.86 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1669968359.A.C84.html
推
12/02 16:18,
3年前
, 1F
12/02 16:18, 1F
討論串 (同標題文章)
完整討論串 (本文為第 124 之 719 篇):