leetcode-20 valid-parentheses(有效的括号)

先看一下题目描述:

通过题目描述可以清楚的明白题目规则,输出true或者false。这道题需要用借用栈来实现,不说理解直接放代码

 1 public boolean isValidParentheses(String s) {
 2         // Write your code here
 3         Stack<Character> stack = new Stack<>();
 4         for (char c : s.toCharArray()) {
 5             if (c == '(' || c == '[' || c == '{') {
 6                 stack.push(c);
 7             }
 8             if (c == ')') {
 9                 if (stack.isEmpty() || stack.pop() != '(') {
10                     return false;
11                 }
12             }
13             if (c == ']') {
14                 if (stack.isEmpty() || stack.pop() != '[') {
15                     return false;
16                 }
17             }
18             if (c == '}') {
19                 if (stack.isEmpty() || stack.pop() != '{') {
20                     return false;
21                 }
22             }
23         }
24         return stack.isEmpty();
25     }
26 }

还有一种进阶版,代码更少,但是思路更犀利,不太容易想到,同样借助栈

 1 public boolean isValid(String s) {
 2         Stack<Character> stack = new Stack<>();
 3         for(char c:s.toCharArray()){
 4             if(c=='('){
 5                 stack.push(')');
 6             }
 7             if(c=='{'){
 8                 stack.push('}');
 9             }
10             if(c=='['){
11                 stack.push(']');
12             }
13             else if(stack.isEmpty()||stack.pop()!=c){
14                 return false;
15             }
16         }
17         return stack.isEmpty();
18     }

其实两段代码思路一模一样,非常巧妙

猜你喜欢

转载自www.cnblogs.com/qingshan0216/p/9994952.html