标签:style blog color os io 使用 ar for div
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.
这题很简单,直接使用栈来进行匹配,代码如下:
1 class Solution { 2 public: 3 bool isValid(string s) { 4 if( s.empty() ) return true; 5 stack<char> st; 6 st.push(‘#‘); 7 for(int i=0; i<s.length(); ++i) 8 if( s[i] == ‘(‘ || s[i] == ‘{‘ || s[i] == ‘[‘ ) //如果是左括号等地字符,那么直接放入栈中 9 st.push(s[i]); 10 else { //如果是右括号等地字符,那么取出栈顶字符,并与是s[i]匹配,如果匹配失败,直接返回false,否则继续比较 11 char ch = st.top(); 12 st.pop(); 13 if( (s[i] == ‘)‘ && ch != ‘(‘) || (s[i] == ‘}‘ && ch != ‘{‘) || (s[i] == ‘]‘ && ch != ‘[‘) ) //匹配不成功的情况 14 return false; 15 } 16 return st.top() == ‘#‘; //如栈顶最后不为#,那么说明左空号等字符过多 17 } 18 };
标签:style blog color os io 使用 ar for div
原文地址:http://www.cnblogs.com/bugfly/p/3951061.html