鍍金池/ 教程/ Java/ Valid Parentheses(有效的括號)
ZigZag Conversion(Z型轉(zhuǎn)換)
String to Integer (atoi)(轉(zhuǎn)換到整型)
Generate Parentheses(生成括號)
Longest Common Prefix(最長公共前綴)
Remove Duplicates from Sorted Array(從已排序數(shù)組中移除重復(fù)元素)
Swap Nodes in Pairs(交換序列中的結(jié)點)
Valid Parentheses(有效的括號)
4 Sum(4 個數(shù)的和)
3 Sum(3 個數(shù)的和)
3 Sum Closest(最接近的 3 個數(shù)的和)
Reverse Nodes in k-Group(在K組鏈表中反轉(zhuǎn)結(jié)點)
Regular Expression Matching (正則表達(dá)式匹配)
Two Sum
Container With Most Water(最大水容器)
Merge Two Sorted Lists(合并兩個已排序的數(shù)組)
Remove Nth Node From End of List(從列表尾部刪除第 N 個結(jié)點)
String to Integer (atoi)(轉(zhuǎn)換到整型)
Palindrome Number(回文數(shù))
Longest Substring Without Repeating Characters
Roman to Integer(羅馬數(shù)到整型數(shù))
Integer to Roman(整型數(shù)到羅馬數(shù))
Reverse Integer(翻轉(zhuǎn)整數(shù))
Merge k Sorted Lists(合并 K 個已排序鏈表)
Implement strStr()(實現(xiàn) strStr() 函數(shù))
Longest Palindromic Substring(最大回文子字符串)
Add Two Numbers
Letter Combinations of a Phone Number(電話號碼的字母組合)

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.

代碼

class Solution {
public:
    bool isValid(string s) {
        if(s.size() % 2 != 0) return 0;
        stack<char> brackets;
        int i = 0;
        while(i < s.size()) {
            if(brackets.empty()) {
                brackets.push(s[i]);
            } else {
                if((brackets.top() == '(' && s[i] == ')') ||
                (brackets.top() == '[' && s[i] == ']') ||
                (brackets.top() == '{' && s[i] == '}')) {
                    brackets.pop();
                } else {
                    brackets.push(s[i]);
                }
            }
            i ++;
        }
        return brackets.size() == 0;
    }
};