leetcode-20 Valid Parentheses
2016-03-25 16:47
363 查看
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.
栈实现括号匹配 (DFS)
//////////////////////////////////////////////////////////////////////////
// start: character matching
bool isValid (string const& s)
{
stack<char> chars;
string left = "([{";
string right = ")]}";
for(auto ch: s)
{
if(left.find(ch) != string::npos)// 如果是左半部分则入栈,如果是右半部分,取出栈顶部分进行匹配
chars.push(ch);
else
{
if(chars.empty() || chars.top() != left[right.find(ch)]) // 如果栈中没有元素或者栈顶元素不匹配则失败
return false; // find函数可以返回下标
else
chars.pop();
}
}
return chars.empty(); // 如果栈中还有元素则也匹配失败
}
// end
//////////////////////////////////////////////////////////////////////////
The brackets must close in the correct order, ”()” and ”()[]” are all valid but ”(]” and ”([)]” are not.
栈实现括号匹配 (DFS)
//////////////////////////////////////////////////////////////////////////
// start: character matching
bool isValid (string const& s)
{
stack<char> chars;
string left = "([{";
string right = ")]}";
for(auto ch: s)
{
if(left.find(ch) != string::npos)// 如果是左半部分则入栈,如果是右半部分,取出栈顶部分进行匹配
chars.push(ch);
else
{
if(chars.empty() || chars.top() != left[right.find(ch)]) // 如果栈中没有元素或者栈顶元素不匹配则失败
return false; // find函数可以返回下标
else
chars.pop();
}
}
return chars.empty(); // 如果栈中还有元素则也匹配失败
}
// end
//////////////////////////////////////////////////////////////////////////
相关文章推荐
- Linux vi/vim 多行注释
- leetcode-19 Remove Nth Node From End of List
- HTTP in iOS你看我就够
- JAVA多线程面试50题 -- 内容由浅及深,全会的是神
- 从零开始_学_数据结构(四)——查找算法、索引、二叉排序树
- jQuery基础-选择图片并赋值
- Sql Server中的表访问方式Table Scan, Index Scan, Index Seek
- SQL Server执行计划教会我如何创建索引?
- mysql的引擎的区别
- WaitForSingleObject函数
- 15电气刘慧岩作业
- redis数据结构详解之Hash(四)
- leetcode-18 4Sum
- 内核中断,异常,抢占总结
- Qt 半自动内存管理引发的内存泄漏和崩溃
- Window下解决端口占用情况
- vmware 虚拟机网络配置
- Android中使用HttpURLConnection实现GET POST JSON数据与下载图片
- 基于spring-jdbc的BaseDao(包含分页)
- Oracle Telnet 1521 失败