Advertisement
LeatherDeer

Untitled

Nov 20th, 2022
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. public boolean isValid(String s) {
  2.  
  3. Stack<Character> leftSymbols = new Stack<>();
  4.  
  5. for (int i = 0; i < s.length(); i++) {
  6. char c = s.charAt(i);
  7. if (c == '(' || c == '{' || c == '[') {
  8. leftSymbols.push(c);
  9. } else {
  10. if (leftSymbols.isEmpty()) return false;
  11.  
  12. char ch = leftSymbols.pop();
  13. if ((ch == '(' && c != ')') ||
  14. (ch == '[' && c != ']') ||
  15. (ch == '{' && c != '}')) {
  16. return false;
  17. }
  18. }
  19. }
  20. return leftSymbols.isEmpty();
  21. }
  22.  
  23. class MyQueue {
  24.  
  25. Stack<Integer> in;
  26. Stack<Integer> out;
  27.  
  28. public MyQueue() {
  29. in = new Stack<>();
  30. out = new Stack<>();
  31. }
  32.  
  33. public void push(int x) {
  34. in.push(x);
  35. }
  36.  
  37. public int pop() {
  38. if (out.isEmpty()) {
  39. while (!in.isEmpty()) {
  40. out.add(in.pop());
  41. }
  42. }
  43. return out.pop();
  44. }
  45.  
  46. public int peek() {
  47. if (out.isEmpty()) {
  48. while (!in.isEmpty()) {
  49. out.add(in.pop());
  50. }
  51. }
  52.  
  53.  
  54. return out.peek();
  55. }
  56.  
  57. public boolean empty() {
  58. return in.isEmpty() && out.isEmpty();
  59. }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement