本文主要是介绍Easy 5 Valid Parentheses(20),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Description
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.
Solution
使用堆栈,压栈时判断是否匹配,若匹配则弹出两个匹配者。这里匹配规则采用ASCII码的一个小trick,即’(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’匹配者满足ASCII相差不大于2。
class Solution {
public:bool isValid(string s) {stack<char> bottle;bottle.push(s[0]);for(int i=1;i<s.size();i++){if((!bottle.empty())&&(s[i]-bottle.top()<=2)&&(s[i]-bottle.top()>0))//若匹配则后者比前者ASCII码值大于0小于2。{bottle.pop();}else{ bottle.push(s[i]); }}return bottle.empty();}
};
这篇关于Easy 5 Valid Parentheses(20)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!