1. 程式人生 > 實用技巧 >LC-1047 Remove All Adjacent Duplicates In String

LC-1047 Remove All Adjacent Duplicates In String

https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/

給一個字串,如果出現兩個相鄰的相同字元,就將它們一同刪去,重複這個操作直到不能繼續做為止,返回最後的字串

一開始我是用類似遞迴的方式重複對這個字串進行操作,結果時間和記憶體都高的嚇人

後來看題解提到了使用棧,這才恍然大悟

這是個比較簡單的小題,記錄在這裡是為了提醒自己對棧的應用

遍歷字串,對每個字元,觀察當前棧頂元素是否與它一樣。如果不是,就入棧;如果是,就不入棧,並且棧pop。

 1 class Solution {
 2 public:
 3     string
removeDuplicates(string S) { 4 stack<char> st; 5 for (int i = 0; i < S.length(); i++) { 6 if (st.empty() || S[i] != st.top()) { 7 st.push(S[i]); 8 } 9 else { 10 st.pop(); 11 } 12 } 13
string ret = ""; 14 while (!st.empty()) { 15 ret.push_back(st.top()); 16 st.pop(); 17 } 18 for (int i = 0; i < ret.length() / 2; i++) { 19 char tmp = ret[i]; 20 ret[i] = ret[ret.length() - 1 - i]; 21 ret[ret.length() - 1
- i] = tmp; 22 } 23 return ret; 24 } 25 };
程式碼