Topic describes

Given a string S consisting of lowercase letters, the deduplication operation selects two adjacent and identical letters and deletes them.

The deduplication operation is repeated on S until the deletion cannot continue.

Returns the final string after all deduplication operations have been completed. Answer guaranteed to be unique

Answer key

Queue assist method:

Queue D is used as a cache to read characters one by one and store them in the cache. Before storing them in the cache, a judgment is needed. If two repeated characters are found to be read, the characters will be deleted from the cache. Finally, the cache is converted to String output.

Execution time: 21 ms, beating 49.74% of all Java commits

Memory consumption: 38.7 MB, beating 94.07% of all Java commits

Pass test case: 106/106

class Solution { public String removeDuplicates(String s) { char[] chars = s.toCharArray(); Deque<Character> d = new ArrayDeque<>(); for (char c : chars) { if (! d.isEmpty() && d.peekLast().equals(c)) { d.pollLast(); } else { d.addLast(c); } } StringBuilder sb = new StringBuilder(); while (! d.isEmpty()) { sb.append(d.pollFirst()); } return sb.toString(); }}Copy the code