原题链接在这里:https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/
题目:
Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them.
We repeatedly make duplicate removals on S until we no longer can.
Return the final string after all such duplicate removals have been made. It is guaranteed the answer is unique.
Example 1:
Input:
Note:
1 <= S.length <= 20000-
Sconsists only of English lowercase letters.
题解:
Follow the instructions, and remove 2 consecutive same chars.
Time Complexity: O(n^2). n = S.length().
Space: O(n).
AC Java:
1 class Solution { 2 public String removeDuplicates(String S) { 3 if(S == null || S.length() == 0){ 4 return S; 5 } 6 7 boolean changed = true; 8 while(changed){ 9 changed = false; 10 StringBuilder sb = new StringBuilder(); 11 int i = 0; 12 while(i < S.length()){ 13 if(i == S.length() - 1 || S.charAt(i) != S.charAt(i + 1)){ 14 sb.append(S.charAt(i)); 15 i++; 16 }else{ 17 changed = true; 18 int j = i + 1; 19 int count = 1; 20 while(j < S.length() && S.charAt(i) == S.charAt(j) && count < 2){ 21 j++; 22 count++; 23 } 24 25 i = j; 26 } 27 } 28 29 S = sb.toString(); 30 } 31 32 return S; 33 } 34 }
跟上Remove All Adjacent Duplicates in String II.