LeetCode 1047. Remove All Adjacent Duplicates In String

原题链接在这里: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: "abbaca"
Output: "ca"
Explanation: 
For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move.  The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".

Note:

  1. 1 <= S.length <= 20000
  2. S consists only of English lowercase letters.

题解:

Have a StringBuilder working as stack. When the last char of StringBuidler is the same as current char, delete it.

Time Complexity: O(n). n = s.length().

Space: O(n).

AC Java:

 1 class Solution {
 2     public String removeDuplicates(String s) {
 3         if(s == null || s.length() < 2){
 4             return s;
 5         }
 6         
 7         StringBuilder sb = new StringBuilder();
 8         for(char c : s.toCharArray()){
 9             if(sb.length() > 0 && sb.charAt(sb.length() - 1) == c){
10                 sb.deleteCharAt(sb.length() - 1);
11             }else{
12                 sb.append(c);
13             }
14         }
15         
16         return sb.toString();
17     }
18 }

Use two points, i and j. j is pointing to current index in s.

i is pointing to result end index.

First arr[i] = arr[j].

When arr[i] == arr[i - 1] then there is a duplicate, set i -= 2.

Time Complexity: O(n).

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         char [] arr = s.toCharArray();
 8         int i = 0;
 9         for(int j = 0; j < s.length(); j++, i++){
10             arr[i] = arr[j];
11             if(i > 0 && arr[i] == arr[i - 1]){
12                 i -= 2;
13             }
14         }
15         
16         return new String(arr, 0, i);
17     }
18 }

跟上Remove All Adjacent Duplicates in String II.

posted @ 2020-02-18 10:33  Dylan_Java_NYC  阅读(364)  评论(0编辑  收藏  举报