1. 程式人生 > >佇列&棧//有效的括號

佇列&棧//有效的括號

給定一個只包括 '('')''{''}''['']' 的字串,判斷字串是否有效。

有效字串需滿足:

  1. 左括號必須用相同型別的右括號閉合。
  2. 左括號必須以正確的順序閉合。

注意空字串可被認為是有效字串。

示例 1:

輸入: "()"
輸出: true

示例 2:

輸入: "()[]{}"
輸出: true

示例 3:

輸入: "(]"
輸出: false

示例 4:

輸入: "([)]"
輸出: false

示例 5:

輸入: "{[]}"
輸出: true

 “{”和“}”的ASCII碼相差2:

class Solution {
    public boolean isValid(String s) {
        if(s == ""||s.length() == 0)
            return true;
        Stack stack = new Stack();
        stack.push(s.charAt(0));
        for(int i = 1; i < s.length(); i++){
            if(!stack.isEmpty()){
                if(stack.peek().equals((char)(s.charAt(i)-1))||stack.peek().equals((char)(s.charAt(i)-2))){
                    stack.pop();
                }else{
                    stack.push(s.charAt(i));
                }
            }else{
                stack.push(s.charAt(i));
            }
        }
        return stack.isEmpty();
    }
}
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 topChar = stack.pop();
                if(ch == ')'&topChar != '(')
                    return false;
                else if(ch == ']'&&topChar != '[')
                    return false;
                else if(ch == '}'&&topChar != '{')
                    return false;
            }
        }
        return stack.isEmpty();
    }
}
class Solution {
public:
    bool isValid(string s) {
        stack<char> result;
        int n = s.size();
        if(n == 0) return true;
        for(int i = 0; i < n; i++){
            if(result.empty())
                result.push(s[i]);
            else if(result.top() == '('&&s[i] == ')'||result.top() == '['&&s[i] == ']'||result.top() == '{'&&s[i] == '}')
                result.pop();
            else
                result.push(s[i]);
        }
        return result.empty();
    }
};
class Solution {
public:
    bool isValid(string s) {
        stack<char> result;
        for(auto &a:s){
            if(a == '(')
                result.push(')');
            else if(a == '[')
                result.push(']');
            else if(a == '{')
                result.push('}');
            else if(result.empty()||result.top()!=a)
                return false;
            else
                result.pop();
        }
        return result.empty();
    }
};