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

20. Valid Parentheses

   

My Submissions
Question Editorial Solution
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 tmp;
		vector 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

你可能感兴趣的:(LeetCode,LeedCode)