1657. 確定兩個(gè)字符串是否接近(面試題打卡/中等)
來(lái)源:力扣(LeetCode)
鏈接:https://leetcode.cn/problems/determine-if-two-strings-are-close
題干:
如果可以使用以下操作從一個(gè)字符串得到另一個(gè)字符串,則認(rèn)為兩個(gè)字符串 接近 :
操作 1:交換任意兩個(gè) 現(xiàn)有 字符。
例如,abcde -> aecdb
操作 2:將一個(gè) 現(xiàn)有 字符的每次出現(xiàn)轉(zhuǎn)換為另一個(gè) 現(xiàn)有 字符,并對(duì)另一個(gè)字符執(zhí)行相同的操作。
例如,aacabb -> bbcbaa(所有 a 轉(zhuǎn)化為 b ,而所有的 b 轉(zhuǎn)換為 a )
你可以根據(jù)需要對(duì)任意一個(gè)字符串多次使用這兩種操作。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-566717.html
給你兩個(gè)字符串,word1 和 word2 。如果 word1 和 word2 接近 ,就返回 true ;否則,返回 false 。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-566717.html
提示:
1 <= word1.length, word2.length <= 105
-
word1
和word2
僅包含小寫(xiě)英文字母
示例:
輸入:word1 = "abc", word2 = "bca"
輸出:true
解釋?zhuān)?span id="n5n3t3z" class="token number">2 次操作從 word1 獲得 word2 。
執(zhí)行操作 1:"abc" -> "acb"
執(zhí)行操作 1:"acb" -> "bca"
輸入:word1 = "a", word2 = "aa"
輸出:false
解釋?zhuān)翰还軋?zhí)行多少次操作,都無(wú)法從 word1 得到 word2 ,反之亦然。
輸入:word1 = "cabbba", word2 = "abbccc"
輸出:true
解釋?zhuān)?span id="n5n3t3z" class="token number">3 次操作從 word1 獲得 word2 。
執(zhí)行操作 1:"cabbba" -> "caabbb"
執(zhí)行操作 2:"caabbb" -> "baaccc"
執(zhí)行操作 2:"baaccc" -> "abbccc"
輸入:word1 = "cabbba", word2 = "aabbss"
輸出:false
解釋?zhuān)翰还軋?zhí)行多少次操作,都無(wú)法從 word1 得到 word2 ,反之亦然。
題解:
- 先判斷長(zhǎng)度,長(zhǎng)度不一樣,肯定不接近
- 用兩數(shù)組記錄字符次數(shù)
- 判斷兩字符串的字符是否都有
- 排序后比較次數(shù)(字符交換的情況)
class Solution {
public static boolean closeStrings(String word1, String word2) {
int len1 = word1.length(), len2 = word2.length();
// 長(zhǎng)度不一致,肯定不接近
if (len1 != len2) return false;
// 分別記錄字符出現(xiàn)的次數(shù)
int[] cnt1 = new int[26];
int[] cnt2 = new int[26];
for (int i = 0; i < len1; i++) {
cnt1[word1.charAt(i) - 'a']++;
}
for (int i = 0; i < len2; i++) {
cnt2[word2.charAt(i) - 'a']++;
}
// 判斷字符是否都有,一個(gè)有一個(gè)沒(méi)有一定不接近
for (int i = 0; i < 26; i++) {
if ((cnt1[i] == 0 && cnt2[i] != 0) || (cnt1[i] != 0 && cnt2[i] == 0)) return false;
}
// 排序后判斷次數(shù)(字符交換的情況)
Arrays.sort(cnt1);
Arrays.sort(cnt2);
for (int i = 0; i < 26; i++) {
if (cnt1[i] != cnt2[i]) return false;
}
return true;
}
}
到了這里,關(guān)于1657. 確定兩個(gè)字符串是否接近的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!