Valid Parentheses
来源:互联网 发布:明日边缘知乎 编辑:程序博客网 时间:2024/05/16 05:09
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.
分析:
使用栈
代码:
#include <iostream>#include <string>#include <stack>#include <algorithm>using namespace std;bool ValidParentTheses(string str){ int len = str.size(); string leftBracket = "([{"; string rightBracket = ")]}"; stack<char> sk; for (int i = 0; i < len; i++) { if (leftBracket.find(str[i]) != string::npos) { sk.push(str[i]); } if (rightBracket.find(str[i]) != string::npos) { if (!sk.empty() && sk.top() == leftBracket[rightBracket.find(str[i])]) { sk.pop(); } else return false; } } if (!sk.empty()) return false; return true;}int main(){ string str = "()"; string str2 = "()[]"; string str3 = "(]"; string str4 = "([)]"; cout << boolalpha << ValidParentTheses(str) << endl; cout << boolalpha << ValidParentTheses(str2) << endl; cout << boolalpha << ValidParentTheses(str3) << endl; cout << boolalpha << ValidParentTheses(str4) << endl; system("pause"); return 0;}
测试:
0 0
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- K - Just a Hook
- 58. Length of Last Word
- Crossed Ladders
- yii2.0 分页(二)
- Unity防反编译的两种手段
- Valid Parentheses
- iOS开发从入门到精通--UIGesture手势基础
- Retrofit使用简介
- 【照虎画猫】京东首页商品菜单列表的实现
- Crossed Ladders
- =="和Equals的区别
- 移动Web整体解决方案
- 数据之美——读书笔记1
- Android通过Window获取View&模拟点击&自定义Toast