[Xiaomi 0923] 2. Loop to remove consecutive repeating elements
Given a string consisting of lowercase letters, find two adjacent and identical letters and delete them.
Repeat the above operation on the character until you can no longer delete it. Output the final string.
Tip
1 <= Input string length <= 20000
Input letters only consist of lowercase letters
.
dbbdut
output
ut
answer
Use stack
import java.util.Scanner;
import java.util.Stack;
public class B {
public static void main(String[] args) {
Stack<Character> stack = new Stack<>();
Scanner in = new Scanner(System.in);
String str = in.nextLine();
for (int i = 0; i < str.length(); i++) {
// 栈空
if (stack.empty()) {
stack.push(str.charAt(i));
}
// 栈非空
else {
// 栈顶元素和当前元素比,一样就消掉
if (stack.peek() == str.charAt(i)) {
stack.pop();
}
// 栈顶元素和当前元素比,不一样就入栈
else {
stack.push(str.charAt(i));
}
}
}
for (Character ch : stack) {
System.out.print(ch);
}
}
}