1. 程式人生 > >LeetCode刷題筆記:有效的括號

LeetCode刷題筆記:有效的括號

Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

An input string is valid if:

  • Open brackets must be closed by the same type of brackets.
  • Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "([)]"
Output: false

解題思路

使用棧來儲存讀入的每一個括號字元,若遇到棧頂與下一個字元是否匹配,若匹配則彈出棧頂元素,否則將下一個字元入棧,遍歷字元結束後看棧內是否還有元素,若沒有則是正確,否則錯誤

Solution

class Solution {
public:
    bool isValid(string s) {
        int size = s.length();
        if(size == 0) return true;
        stack<char> container;
        container.push(s[0]);
        for(int i = 1; i < size; ++i) {
            if(!container.empty()) {
                if(container
.top() == '(' && s[i] == ')') { container.pop(); }else if(container.top() == '{' && s[i] == '}'){ container.pop(); }else if(container.top() == '[' && s[i] == ']') { container.pop(); }else { container.push(s[i]); } }else { container.push(s[i]); } } if(container.empty()) { return true; }else { return false; } } };