【LeetCode】LeetCode——第20题:Valid Parentheses

来源:互联网 发布:公需科目大数据网站 编辑:程序博客网 时间:2024/05/16 04:08

20. Valid Parentheses

   

My Submissions
Total Accepted: 106450 Total Submissions: 361988 Difficulty: Easy

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

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.








题目的大概意思是:给定一个括号字符串s,判断该字符串括号是否是有效的。

这道题难度等级:简单

思路:对字符串进行逐一判断,使用堆栈的思想可以做。当然,为了用空间换取时间,我这里做了一个表,使用查表法即可。

class Solution {public:    bool isValid(string s) {vector<char> tmp;vector<char> table(255, 0);table['('] = table[')'] = 1;table['['] = table[']'] = 2;table['{'] = table['}'] = 3;int i = 0;for (i = 0; i < s.length(); ++i){if (s[i] == '(' || s[i] == '[' || s[i] == '{'){tmp.push_back(s[i]);}else if (s[i] == ')' || s[i] == ']' || s[i] == '}'){if (tmp.empty() || table[s[i]] != table[tmp[tmp.size() - 1]]){return false;}tmp.pop_back();}}return tmp.empty() ? true : false;    }};
提交代码,AC掉,Runtime:0ms

0 0