Re: [閒聊] 每日LeetCode已回收
1544. Make The String Great
龍大是個字串處理員他會收到很多字串,如果這個字串壞掉了他就要把字串壞掉的部分切
掉,一個字串是「好」的他必須滿足:
* 任意兩個相鄰字串不可以是一個大寫一個小寫的英文字母
例如:leE(eE是壞的所以要切掉讓他變l)
字串只包含大小寫英文字母。
Example1:
Input: s = "leEeetcode"
Output: "leetcode"
Explanation: In the first step, either you choose i = 1 or i = 2, both will
result "leEeetcode" to be reduced to "leetcode".
Example2:
Input: s = "abBAcC"
Output: ""
Explanation: 刪除的順序可能有多種:
"abBAcC" --> "aAcC" --> "cC" --> ""
"abBAcC" --> "abBA" --> "aA" --> ""
思路:
1.大寫字母可以和小寫字母「兩兩消除」,我們可以聯想到刮號問題,所以這題很明顯
是要用stack來解。
2.先寫一個判斷兩字元是否是大小寫字母的函數。
3.分成兩個case:
* stack為空
把當前字母push進stack
* stack不為空
就把當前字母與stack頂端比較,如果可以消除(一個大寫一個小寫)就從stack
中pop出一個元素,否則把當前字母push進stack
4.如果字串都處理完了,因為stack的特性所以原字串拿出來的時候順序相反,我們把
stack裡的字元全部pop出來,並且倒序構建字串就是解字串了。
JavaCode:
----------------------------------------------------------
class Solution {
public String makeGood(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
if (stack.isEmpty() || isNotBad(stack.peek(), s.charAt(i))) {
stack.push(s.charAt(i));
} else {
stack.pop();
}
}
char[] chars = new char[stack.size()];
for (int i = stack.size() - 1; i >= 0; i--) {
chars[i] = stack.pop();
}
return new String(chars);
}
private boolean isNotBad(char c1, char c2) {
return Math.abs(c1 - c2) != 32;
}
}
-----------------------------------------------------------
https://i.imgur.com/BtsJXgg.gif


--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.160.66.39 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1667870871.A.48D.html
※ 編輯: Rushia (1.160.66.39 臺灣), 11/08/2022 09:29:46
推
11/08 09:30,
3年前
, 1F
11/08 09:30, 1F
※ 編輯: Rushia (1.160.66.39 臺灣), 11/08/2022 09:34:46
推
11/08 09:38,
3年前
, 2F
11/08 09:38, 2F
→
11/08 09:39,
3年前
, 3F
11/08 09:39, 3F
→
11/08 09:40,
3年前
, 4F
11/08 09:40, 4F
→
11/08 09:46,
3年前
, 5F
11/08 09:46, 5F
→
11/08 09:46,
3年前
, 6F
11/08 09:46, 6F
→
11/08 09:50,
3年前
, 7F
11/08 09:50, 7F
推
11/08 13:13,
3年前
, 8F
11/08 13:13, 8F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 90 之 719 篇):