LaiCode 82. Remove Adjacent Repeated Characters IV
题目
思路
- First, we need a stack to store elements which need to be in the output.
- Then we need to put the string into a character array, and traverse the whole array. In the meanwhile, we need to put unique element in to the stack and to check each element if it is the same as the top element of the stack.
- If the element is different from the top element of the stack, then we should push it into the stack; And if the element is the same as the top element of the stack, we move the pointer to the next element, until we find the different one or we reach the end of the array.
- Finally, we need an another array to put the elements in the stack into it, and construct a string with the array.
代码
public class Solution {
public String deDup(String input) {
// Write your solution here
// Corner case
if (input == null || input.length() <= 1) {
return input;
}
char[] str = input.toCharArray();
Deque<Character> stack = new ArrayDeque<>();
for (int i = 0; i < str.length; ) {
char curChar = str[i];
if (!stack.isEmpty() && stack.peekFirst() == curChar) {
while (i < str.length && str[i] == curChar) {
i++;
}
stack.pollFirst();
} else {
stack.offerFirst(str[i++]);
}
}
// Post processing
int len = stack.size();
int[] ans = new int[len];
for (int i = len - 1; i >= 0; i--) {
ans[i] = stack.pollFirst();
}
return new String(ans, 0, len);
}
}
分析
The time complexity is O(n), and the n is the length of the input.
The space complexity is O(n), because it need an character array, a stack and a post processing array.