作者Rushia (みけねこ的鼻屎)
看板Marginalman
標題Re: [閒聊] 每日LeetCode
時間Mon Jul 3 23:38:23 2023
https://leetcode.com/problems/buddy-strings/
859. Buddy Strings
給你一個字串 s 和一個字串 goal,如果 s 的兩個字元交換一次後等於 goal 則他是
一個 Buddy Strings,判斷 s 是否是一個 Buddy Strings。
Example 1:
Input: s = "ab", goal = "ba"
Output: true
Explanation: You can swap s[0] = 'a' and s[1] = 'b' to get "ba", which is
equal to goal.
Example 2:
Input: s = "ab", goal = "ab"
Output: false
Explanation: The only letters you can swap are s[0] = 'a' and s[1] = 'b',
which results in "ba" != goal.
Example 3:
Input: s = "aa", goal = "aa"
Output: true
Explanation: You can swap s[0] = 'a' and s[1] = 'a' to get "aa", which is
equal to goal.
思路:
1.一個一個排掉corner case
Java Code:
-------------------------------------------------
class Solution {
public boolean buddyStrings(String s, String goal) {
// 如果兩個字串長度不同怎麼交換都失敗
if (s.length() != goal.length()) {
return false;
}
// 比較s和goal不同的字元數
int notSame = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != goal.charAt(i)) {
notSame++;
}
}
// 不同的數量大於兩個怎麼交換都失敗
if (notSame > 2) {
return false;
}
// 統計字母數
int[] cnt1 = new int[26];
int[] cnt2 = new int[26];
for (int i = 0; i < s.length(); i++) {
cnt1[s.charAt(i) - 'a']++;
cnt2[goal.charAt(i) - 'a']++;
}
// 檢查字母數有幾個相同
int same = 0;
for (int i = 0; i < 26; i++) {
if (cnt1[i] == cnt2[i]) {
same++;
}
}
// 如果數量全相同只要有任意字母數量大於2就可以原地交換
if (same == 26) {
for (int i = 0; i < 26; i++) {
if (cnt1[i] > 1) {
return true;
}
}
}
// 找到第一個不同的字元,如果s和goal有相同數量的字元則合法
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != goal.charAt(i)) {
return cnt1[s.charAt(i) - 'a'] == cnt2[s.charAt(i) - 'a']
&& cnt1[goal.charAt(i) - 'a'] == cnt2[goal.charAt(i)
- 'a'];
}
}
return false;
}
}
-------------------------------------------------
難度:easy
幹你娘機掰
漬鯊 ==
--
https://i.imgur.com/PIoxddO.jpg
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.100.75.86 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1688398706.A.1C4.html
→ lopp54321010: 好粗暴的easy哦 07/03 23:40
推 JIWP: 大師 07/03 23:43
推 Che31128: 這題真的很粗暴 07/03 23:55
推 NTHUlagka: code應該可以簡化 沒用到NotSame 只能等於2或0的情況 07/04 12:44
→ NTHUlagka: 去做區分小可惜 07/04 12:44