for (inti=0; i < s.length(); i++) { charc1= s.charAt(i); // if this char is left side, push it into stack if (c1 == '(' || c1 == '[' || c1 == '{') { stack.push(c1); }else {
// if stack is empty and a right side char comes // return false if (stack.isEmpty()) { returnfalse; }
// else let's check if there is a pair charc2= stack.pop(); if ( c1 == ')' && c2 == '(' || c1 == ']' && c2 == '[' || c1 == '}' && c2 == '{') { continue; }else { returnfalse; } } } // if after checking, there is no chars left in the stack // it means that they are all pairs return stack.isEmpty();
classSolution { public String removeDuplicates(String s) {
char[] chars = s.toCharArray(); Stack<Character> stack = newStack<>(); // full scan the whole string for (char c : chars) { // if stack is not empty, pop the top element // compare if it is the same with the pointed one // if not push them back if (!stack.empty()) { charc2= stack.pop(); if (c2 != c){ stack.push(c2); stack.push(c); } }else { stack.push(c); } } // pop the left elements if (!stack.isEmpty()){ intsize= stack.size(); char[] ans = newchar[size]; while (size > 0) { ans[--size] = stack.pop(); }