LeetCode算法题20:有效的括号解析

给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:

  • 左括号必须用相同类型的右括号闭合。
  • 左括号必须以正确的顺序闭合。

注意空字符串可被认为是有效字符串。
示例1:

输入: "()"
输出: true

示例2:

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

示例3:

输入: "(]"
输出: false

示例4:

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

示例5:

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

这个题从一开始就觉得应该用递归,但是一开始想的确是递归函数,因为之前只知道栈而从没用过,所以又学到新的东西啦~
解题的经典思路是使用栈去存储左括号,然后遇到右括号时检查是否与栈顶元素匹配,如果不匹配那就说明这个字符串不是有效的括号。另外如果栈为空时遇到了右括号,那说明也不是有效字符串。然后遍历完所有字符串后再检查一下栈,如果栈为空,说明所有括号都匹配完毕,为有效括号。如果栈不为空就是无效括号。(程序中增加了奇偶检测,增加效率)
C++源代码:

class Solution {
public:
    bool isValid(string s) {
        stack<char> temp;
        map<char, char> m;
        m['{'] = '}';
        m['('] = ')';
        m['['] = ']';
        if (s.length() % 2 != 0)
            return false;
        for (char i : s)
        {
            if (i == '(' || i == '{' || i == '[')
                temp.push(i);
            else
            {
                if (temp.empty())
                    return false;
                if (m[temp.top()] == i)
                    temp.pop();
                else
                    return false;
            }
        }
        if (temp.empty())
            return true;
        else
            return false;
    }
};

python3源代码:

class Solution:
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        m = {'{': '}', '(': ')', '[': ']'}
        temp = []
        # if len(s) % 2 != 0:
        #     return False
        for i in s:
            if i in m.keys():
                temp.append(i)
            else:
                if len(temp) == 0:
                    return False
                if m[temp[-1]] == i:
                    temp.pop()
                else:
                    return False
        return not temp

猜你喜欢

转载自blog.csdn.net/x603560617/article/details/83340437