LeetCode刷题 20 有效的括号

题目

给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需知足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "(]"
输出: false
示例 4:
输入: "([)]"
输出: false
示例 5:
输入: "{[]}"
输出: true

思考

看到这题的第一反应就是,正常来讲,正确的括号的话,那么必须是一一对应的,那若是左括号为1,右括号为-1的话,那么和为0。从这个想法出发,个人解法以下。python

解题思路

  1. 先创建括号的对应值的字典,左为正,右为负。
  2. 将得到的括号字符串转换成数字数组
  3. 先求sum,不为零就说明不是有效括号,返回
  4. 遍历数字数组,若是获得是正数,就push到新数字数组的最后
  5. 若是是负数就判断,这个负数跟新数字数组的最后一位相加是否为零,是的话pop新数组最后一位
  6. 若是相加不为零则说明括号没有一一对应,返回

Python实现

class Solution:
    def isValid(self, s: str) -> bool:
        d = {'(' : 1, ')' : -1, '[' : 2, ']' : -2, '{' : 3, '}' : -3}
        changeNumList = [d[c] for c in s]
        if 0 != sum(changeNumList):
            return False
        
        tempList = list()
        for i in changeNumList:
            if i > 0:
                tempList.append(i)
            else:
                if len(tempList) > 0:
                    if (tempList[-1] + i) != 0:
                        return False
                    else:
                        tempList.pop()
                    
        if len(tempList) > 0:
            return False
        
        return True

执行用时 :48 ms, 在全部 Python3 提交中击败了80.77%的用户,内存消耗 :13.8 MB, 在全部 Python3 提交中击败了5.51%的用户c++

C++实现

#include<map>
#include<vector>

class Solution 
{
public:
    bool isValid(string s) 
    {
        std::map<char, int> changeNumMap = {{'(', 1}, {')', -1}, {'[', 2}, {']', -2}, {'{', 3}, {'}', -3}};
        std::vector<int> numList;
        
        int sum = 0;
        for(int i = 0; s[i] != '\0'; ++i)
        {
            numList.push_back(changeNumMap[s[i]]);
            sum += numList[i];
        }
        
        if(sum != 0)    return false;
        
        std::vector<int> tempNumList;
        for(auto it = numList.begin(); it != numList.end(); ++it)
        {
            if((*it) > 0)
            {
                tempNumList.push_back((*it));
            }
            else
            {
               if(tempNumList.size() > 0)
               {
                   if((tempNumList.back() + (*it)) != 0)
                   {
                       return false;
                   }
                   else
                   {
                       tempNumList.pop_back();
                   }
               }
            }
        }
        
        if(tempNumList.size() > 0)  return false;
        
        return true;
    }
};

执行用时 :4 ms, 在全部 C++ 提交中击败了79.60%的用户,内存消耗 :8.7 MB, 在全部 C++ 提交中击败了66.25%的用户数组

相关文章
相关标签/搜索