Advertisement
LeatherDeer

Untitled

Nov 19th, 2022
559
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.69 KB | None | 0 0
  1.     public static boolean isValid(String s) {
  2.         if (s == null || s.length() % 2 != 0) {
  3.             return false;
  4.         }
  5.         Stack<Character> stack = new Stack<>();
  6.         for (Character curCh : s.toCharArray()) {
  7.             if (curCh == '(' || curCh == '[' || curCh == '{') {
  8.                 stack.push(curCh);
  9.             } else  {
  10.                 if (stack.isEmpty()) return false;
  11.                
  12.                 char ch = stack.pop();
  13.                 if ((curCh == ')' && ch != '(') || (curCh == '}' && ch != '{') || (curCh == ']' && ch != '[')) {
  14.                     return false;
  15.                 }
  16.             }
  17.         }
  18.        
  19.         return stack.isEmpty();
  20.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement