Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public boolean isValid(String s) {
- Stack<Character> leftSymbols = new Stack<>();
- for (int i = 0; i < s.length(); i++) {
- char c = s.charAt(i);
- if (c == '(' || c == '{' || c == '[') {
- leftSymbols.push(c);
- } else {
- if (leftSymbols.isEmpty()) return false;
- char ch = leftSymbols.pop();
- if ((ch == '(' && c != ')') ||
- (ch == '[' && c != ']') ||
- (ch == '{' && c != '}')) {
- return false;
- }
- }
- }
- return leftSymbols.isEmpty();
- }
- class MyQueue {
- Stack<Integer> in;
- Stack<Integer> out;
- public MyQueue() {
- in = new Stack<>();
- out = new Stack<>();
- }
- public void push(int x) {
- in.push(x);
- }
- public int pop() {
- if (out.isEmpty()) {
- while (!in.isEmpty()) {
- out.add(in.pop());
- }
- }
- return out.pop();
- }
- public int peek() {
- if (out.isEmpty()) {
- while (!in.isEmpty()) {
- out.add(in.pop());
- }
- }
- return out.peek();
- }
- public boolean empty() {
- return in.isEmpty() && out.isEmpty();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement