2016.6.17——Valid Parentheses
2016-06-17 19:52
190 查看
Valid Parentheses
本题收获:1.stack的使用
2.string和char的区别
题目:
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.
注意题目中只是输入了一个字符串 如:“{}(]” 而不是{“{}[”,"[]"}
思路:
leetcode:用stack,括号为左边压入栈,右边的和栈顶对比,所有的都匹配返回true,不匹配返回false
代码:
bool isValid(string s) { stack<char> st; for(char c : s){ if(c == '('|| c == '{' || c == '['){ st.push(c); }else{ if(st.empty()) return false; if(c == ')' && st.top() != '(') return false; if(c == '}' && st.top() != '{') return false; if(c == ']' && st.top() != '[') return false; st.pop(); } } return st.empty();
我的测试代码:
class MyClass { public: bool isValid(string str) { stack<char> st; //is <char> not<string> for (size_t i = 0; i < str.size(); i++) { if (str[i] == '(' || str[i] == '{' || str[i] == '[') { st.push(str[i]); } else { if (str[i] == ')' && st.top() != '(') return false; if (str[i] == ']' && st.top() != '[') return false; if (str[i] == '}' && st.top() != '{') return false; //不写st.pop()有什么差别 } } return true; //st.empty() } };
完整代码:
// Valid Parentheses.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "iostream" #include "stack" #include "stack" using namespace std; class MyClass { public: bool isValid(string str) { stack<char> st; //is <char> not<string> 栈的定义,注意是string/char for (size_t i = 0; i < str.size(); i++) { if (str[i] == '(' || str[i] == '{' || str[i] == '[') { st.push(str[i]); } else { if (str[i] == ')' && st.top() != '(') return false; if (str[i] == ']' && st.top() != '[') return false; //st.top(),有括号“,”栈的.后面都有() if (str[i] == '}' && st.top() != '{') return false; //不写st.pop()有什么差别 } } return true; //st.empty() } }; /* class MyClass { public: bool isValid(string str) { stack<char> st; //is <char> not<string> for (char c : str) { if (c == '(' || c == '{' || c == '[') { st.push(c); } else { if (c == ')' && st.top() != '(') return false; if (c == ']' && st.top() != '[') return false; if (c == '}' && st.top() != '{') return false; st.pop(); } } return st.empty(); } };*/ int _tmain(int argc, _TCHAR* argv[]) { string str = "({[]})"; int m = 0; MyClass solution; m = solution.isValid(str); cout << m << endl; system("pause"); return 0; }
相关文章推荐
- ORA-12560: TNS: 协议适配器错误
- django后台启动+log重定向命令
- 常用KeyCode
- debug找不到源码问题 edit lookup path
- 如何配置一个简易的密码弹出框Dialog
- linux常用操作
- 欢迎使用CSDN-markdown编辑器
- 抽象类(接口类)的作用
- 基于Bootstrap和Knockout.js的ASP.NET MVC开发实战
- python之删除30天以前的文件
- 作业补做
- 数组元素排序问题!
- java提高篇(一)-----理解java的三大特性之封装
- Poj 1144 Network【Tarjan求割点】
- leetcode 5. Longest Palindromic Substring
- MYSQL 递归实现
- OpenCV 读取 CSV 数据文件
- 倍增法-lca codevs 1036 商务旅行
- C++_模板类的友元运算符重载_原理
- 【bzoj2141】【排队】【树状数组套平衡树】