天天看點

LeetCode 20. Valid Parentheses(括号校驗)

原題網址:https://leetcode.com/problems/valid-parentheses/

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 class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        for(int i=0; i<s.length(); i++) {
            char ch = s.charAt(i);
            if (ch == '(' || ch == '[' || ch == '{') stack.push(ch);
            else {
                if (stack.isEmpty()) return false;
                char last = stack.pop();
                if ((last == '(' && ch == ')') || (last == '[' && ch == ']') || (last == '{' && ch == '}')) continue;
                return false;
            }
        }
        return stack.isEmpty();
    }
}
           

另一種實作:使用數組實作棧。

public class Solution {
    public boolean isValid(String s) {
        char[] sa = s.toCharArray();
        int stack = 0;
        for(int i=0; i<sa.length; i++) {
            if (sa[i]=='(' || sa[i]=='[' || sa[i]=='{') sa[stack++] = sa[i];
            else if (stack == 0) return false;
            else if (sa[stack-1] != '(' && sa[i]==')') return false;
            else if (sa[stack-1] != '[' && sa[i]==']') return false;
            else if (sa[stack-1] != '{' && sa[i]=='}') return false;
            else stack --;
        }
        return stack == 0;
    }
}