> For the complete documentation index, see [llms.txt](https://emmaguo100.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://emmaguo100.gitbook.io/leetcode/02-11-2022-1047.md).

# 02/11/2022 1047

Method 1:

Use two pointers, i is for index iterate the String. j is for the result string index. In the for loop, set ans\[j] = S\[i], If j >0 and ans\[j] == ans\[j-1], then j--, else j++. Finally return the string from index 0 to j.

Time O(n)

Space O(1)

```
class Solution {
    public String removeDuplicates(String S) {
        if(S == null || S.length() == 0) {
            return S;
        }
        int j = 0;
        int n = S.length();
        char[] ans = new char[n];
        
        for(int i = 0; i < n; i++) {
            ans[j] = S.charAt(i);
            if(j > 0 && ans[j] == ans[j - 1]) {
                j--;
            } else {
                j++;
            }
        }
        return new String(ans, 0, j);
    }
}
```

Method 2:

Use StringBuilder as a stack. When the size of sb is > 0, check if sb\[size - 1] == the current character. If it is, delete the character at the size - 1. Otherwise, append the character to the sb.

Time O(n)

Space O(N)

```
public String removeDuplicates(String S) {
        StringBuilder sb = new StringBuilder();
        for (char c : S.toCharArray()) {
            int size = sb.length();
            if (size > 0 && sb.charAt(size - 1) == c) { 
                sb.deleteCharAt(size - 1); 
            }else { 
                sb.append(c); 
            }
        }
        return sb.toString()
```

Method 3:

Use stack and StringBuilder. Similar way with the second method.

Time O(n)

Space O(n)

```

// Some code
class Solution { 
    public String removeDuplicates(String s) { 
        char[] arr = s.toCharArray(); 
        Stack stack = new Stack<>(); 
        for(int i = 0; i < arr.length; i++){ 
            if(stack.isEmpty() || stack.peek() != arr[i]){ 
                stack.push(arr[i]); 
            }else{ 
                stack.pop(); 
                } 
        } 
        StringBuilder str = new StringBuilder(); 
        for(char ch: stack){ 
            str.append(ch); 
        } 
        return str.toString(); 
        } 
    }
```
