Re: [閒聊] 每日LeetCode已回收
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
→
07/03 23:40,
2年前
, 1F
07/03 23:40, 1F
推
07/03 23:43,
2年前
, 2F
07/03 23:43, 2F
推
07/03 23:55,
2年前
, 3F
07/03 23:55, 3F
推
07/04 12:44,
2年前
, 4F
07/04 12:44, 4F
→
07/04 12:44,
2年前
, 5F
07/04 12:44, 5F
討論串 (同標題文章)
完整討論串 (本文為第 359 之 719 篇):