1. 程式人生 > >LeetCode演算法學習(8)

LeetCode演算法學習(8)

題目描述

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

An input string is valid if:

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

Note that an empty string is also considered valid.

題目大意

括號匹配。

思路分析

簡單的棧的應用。

關鍵程式碼

    bool match(char a, char b) {
        if (a == '(') return b == ')';
        if (a == '[') return b == ']';
        if (a == '{') return b == '}';
        return false;
    }

    bool isValid(string s)
{ stack<char> stack1; int n = s.length(); for (int i = 0; i < n; i++) { if (s[i] == '(' || s[i] == '[' || s[i] == '{') { stack1.push(s[i]); } else if (stack1.empty()) { return false; } else { if
(match(stack1.top(), s[i])) { stack1.pop(); } else { return false; } } } if (stack1.empty()) { return true; } else { return false; } }

總結

當複習棧吧。