20. Valid Parentheses

xiaoxiao2021-02-28  4

Given a string containing just the characters  '(' ')' '{' '}' '['  and  ']' , determine if the input string is valid. The brackets must close in the correct order,  "()"  and  "()[]{}"  are all valid but  "(]"  and  "([)]"  are not. 验证一个字符串里的括号是否正确闭合 比较简单 代码如下 public boolean isValid(String s) { Stack<Character> stack = new Stack<Character>(); for(char c : s.toCharArray()){ switch (c){ case '(': case '{': case '[': stack.push(c); break; case ')': if(stack.isEmpty() || stack.pop() != '(') return false; break; case '}': if(stack.isEmpty() || stack.pop() != '{') return false; break; case ']': if(stack.isEmpty() || stack.pop() != '[') return false; break; } } return stack.isEmpty(); } 代码已经很简洁了 但是没想到还有更骚的 public boolean isValid(String s) { Stack<Character> stack = new Stack<Character>(); for (char c : s.toCharArray()) { if (c == '(') stack.push(')'); else if (c == '{') stack.push('}'); else if (c == '[') stack.push(']'); else if (stack.isEmpty() || stack.pop() != c) return false; } return stack.isEmpty(); }每次遇到左括号就向stack中放入右括号 遇到右括号直接和栈顶比较是否相等
转载请注明原文地址: https://www.6miu.com/read-1750042.html

最新回复(0)