Re: [閒聊] 每日LeetCode已回收

看板Marginalman作者 (みけねこ的鼻屎)時間1年前 (2024/01/14 17:04), 1年前編輯推噓1(100)
留言1則, 1人參與, 1年前最新討論串602/719 (看更多)
https://leetcode.com/problems/determine-if-two-strings-are-close/description 1657. Determine if Two Strings Are Close 給你兩個字串word1和word2,你可以對他們坐下面的兩個操作: 1.替換word中字元的位置 例如:abc -> cba 2.將字串中的某個字元和另一個字元全部交換 例如:aabbb -> bbbaa 求出word1和words2經過上面兩個操作後是否可以相等。 思路: 1.字串長度不同不可能相等先排除掉。 2.因為可以任意替換word字元的位置,所以我們先統計所有字元的數量,再來只要滿足兩 個條件: 一、word1有的字元word2也有 二、word1每個字母的字元數量排列後和word2的字元數量相等(交換) 3.計算兩者的字元數量並排序檢查數量是否匹配即可。 Java Code: ------------------------------------------- class Solution { public boolean closeStrings(String word1, String word2) { if (word1.length() != word2.length()) { return false; } int[] cnt1 = new int[26]; int[] cnt2 = new int[26]; for (int i = 0; i < word1.length(); i++) { cnt1[word1.charAt(i) - 'a']++; cnt2[word2.charAt(i) - 'a']++; } for (int i = 0; i < 26; i++) { if (cnt1[i] > 0 && cnt2[i] == 0) { return false; } } Arrays.sort(cnt1); Arrays.sort(cnt2); for (int i = 0; i < 26; i++) { if (cnt1[i] != cnt2[i]) { return false; } } return true; } } ------------------------------------------- -- https://i.imgur.com/PIoxddO.jpg
-- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.100.73.13 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1705223095.A.160.html

01/14 17:05, 1年前 , 1F
大師
01/14 17:05, 1F
※ 編輯: Rushia (122.100.73.13 臺灣), 01/14/2024 17:05:38
文章代碼(AID): #1bewEt5W (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1bewEt5W (Marginalman)