1. 程式人生 > >leetcode-20 valid-parentheses(有效的括號)

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     }

其實兩段程式碼思路一模一樣,非常巧妙