Skip to content

Latest commit

 

History

History
83 lines (71 loc) · 2.31 KB

1047. Remove All Adjacent Duplicates In String.md

File metadata and controls

83 lines (71 loc) · 2.31 KB

leetcode Daily Challenge on March 9th, 2021.


Difficulty : Easy

Related Topics : Stack


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 <= S.length <= 20000
  • S consists only of English lowercase letters.

Solution

  • mine
    • Java
      • Runtime: 16 ms, faster than 54.97%, Memory Usage: 39.5 MB, less than 74.65% of Java online submissions
        // O(N)time
        // O(N)space
        public String removeDuplicates(String S) {
            LinkedList<Character> list = new LinkedList<>();
            char[] arr = S.toCharArray();
            for (char c : arr) {
                if (!list.isEmpty() && list.getLast() == c) {
                    list.removeLast();
                } else {
                    list.addLast(c);
                }
            }
            if (list.size() == 0) return "";
            StringBuilder sb = new StringBuilder();
            while (list.size() != 0) sb.append(list.removeFirst());
            return sb.toString();
        }
        

  • the most votes
  • Runtime: 3 ms, faster than 99.72%, Memory Usage: 39.9 MB, less than 38.69% of Java online submissions
    // O(N)time
    // O(N)space
    public String removeDuplicates(String S) {
        char[] chars = S.toCharArray();
        int writeIndex = -1;
        for (char c : chars) {
            if (writeIndex >= 0 && c == chars[writeIndex]) {
                writeIndex--;
            } else {
                chars[++writeIndex] = c;
            }
        }
        return String.valueOf(chars, 0, writeIndex + 1);
    }