Valid Parentheses
2015-08-12 11:06
417 查看
Given a string containing just the characters
determine if the input string is valid.
The brackets must close in the correct order,
all valid but
not.
版本二
class Solution {
public:
bool isValid(string s)
{
int len = s.size();
if(len == 0)
{
return true;
}
stack<char> st;
for(int i = 0; i < len; ++ i)
{
if(s[i] == '(' || s[i] == '[' || s[i] == '{')
{
st.push(s[i]);
continue;
}
if((s[i] == ')' || s[i] == ']' || s[i] == '}') && st.empty())
{
return false;
}
if(s[i] == ')')
{
if(st.top() == '(')
{
st.pop();
}else
{
return false;
}
continue;
}
if(s[i] == ']')
{
if(st.top() == '[')
{
st.pop();
}else
{
return false;
}
continue;
}
if(s[i] == '}')
{
if(st.top() == '[')
{
st.pop();
}else
{
return false;
}
continue;
}
}
if(st.empty())
{
return true;
}else
{
return false;
}
}
};
'(',
')',
'{',
'}',
'['and
']',
determine if the input string is valid.
The brackets must close in the correct order,
"()"and
"()[]{}"are
all valid but
"(]"and
"([)]"are
not.
bool isValid(string s) { int l=s.size(); stack<char> st; if(s.empty()) return true; if(s[0]==')'||s[0]==']'||s[0]=='}') return false; if(l%2==1) return false; for(int i=0;i<l;i++){ if(s[i]=='('||s[i]=='['||s[i]=='{') st.push(s[i]); if(s[i]==')'){ if(st.top()!='(') return false; else st.pop(); } if(s[i]==']'){ if(st.top()!='[') return false; else st.pop(); } if(s[i]=='}'){ if(st.top()!='{') return false; else st.pop(); } } if(st.empty()) return true; return false; }
版本二
class Solution {
public:
bool isValid(string s)
{
int len = s.size();
if(len == 0)
{
return true;
}
stack<char> st;
for(int i = 0; i < len; ++ i)
{
if(s[i] == '(' || s[i] == '[' || s[i] == '{')
{
st.push(s[i]);
continue;
}
if((s[i] == ')' || s[i] == ']' || s[i] == '}') && st.empty())
{
return false;
}
if(s[i] == ')')
{
if(st.top() == '(')
{
st.pop();
}else
{
return false;
}
continue;
}
if(s[i] == ']')
{
if(st.top() == '[')
{
st.pop();
}else
{
return false;
}
continue;
}
if(s[i] == '}')
{
if(st.top() == '[')
{
st.pop();
}else
{
return false;
}
continue;
}
}
if(st.empty())
{
return true;
}else
{
return false;
}
}
};
相关文章推荐
- Linux命令详解 -- iptables
- linux中查找对应结构或者变量
- Algorithms—129.Sum Root to Leaf Numbers
- Android 文件操作总结
- HTTP、TCP、UDP、Socket基本概念
- iOS新手必看之全貌
- Sql Server的存储过程基本知识
- java设计模式之原型模式
- 访问者模式
- Spring中控制反转实例
- LeetCode题解:Rectangle Area
- jquery中attr和prop的区别
- IOS中的Propety(点语法,属性)
- drupal 数据库查询的两种方式 奇
- javafx KeyCombination
- Python代码运行助手
- Dynamics CRM 开启EmailRouter日志记录
- Dynamics CRM 开启EmailRouter日志记录
- Dynamics CRM 开启EmailRouter日志记录
- Dynamics CRM 开启EmailRouter日志记录