LeetCode Problem -- 20. Valid Parentheses

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_38088298/article/details/85854314
  • 描述: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: true

  • 分析:给出一个表达式只含有‘(’‘[’‘{’三种括号,要求判断此表达式是否符合括号匹配规则:
    1.括号类型匹配
    2.括号顺序匹配
  • 思路一:使用栈来解决。如果遇到‘(’‘[’‘{’三种开括号,就将它们push进栈,遇到‘)’‘]’‘}’三种开括号,判断栈顶元素是否是与之匹配的开括号,是则将栈顶元素pop出去,不是则return false。
class Solution {
public:
    bool isValid(string s) {
        stack<char> character_match;
        for (int i = 0; i < s.size(); i++) {
            if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
            character_match.push(s[i]);
            }
            if (s[i] == ')') {
                if (!character_match.empty() && character_match.top() == '(') character_match.pop();
                else return false;
            }
            if (s[i] == ']') {
                if (!character_match.empty() && character_match.top() == '[') character_match.pop();
                else return false;
            }
            if (s[i] == '}') {
                if (!character_match.empty() && character_match.top() == '{') character_match.pop();
                else return false;
            }
        }
        return character_match.empty();
    }
};
  • 思路二:用map优化一下代码。
class Solution {
public:
    bool isValid(string s) {
        stack<char> character_match;
        map<char, char> char_mapping;
        char_mapping.insert(make_pair(')', '('));
        char_mapping.insert(make_pair(']', '['));
        char_mapping.insert(make_pair('}', '{'));
        for (int i = 0; i < s.size(); i++) {
            if (s[i] == '(' || s[i] == '[' || s[i] == '{') character_match.push(s[i]);
            else if (!character_match.empty() && char_mapping.find(s[i]) != char_mapping.end() && character_match.top() == char_mapping[s[i]]) character_match.pop();
            else return false;
        }
        return character_match.empty();
    }
};

猜你喜欢

转载自blog.csdn.net/m0_38088298/article/details/85854314
今日推荐