给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需知足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "(]"
输出: false
示例 4:
输入: "([)]"
输出: false
示例 5:
输入: "{[]}"
输出: true
看到这题的第一反应就是,正常来讲,正确的括号的话,那么必须是一一对应的,那若是左括号为1,右括号为-1的话,那么和为0。从这个想法出发,个人解法以下。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++
#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%的用户数组