算法设计与分析(14)-- Valid Parentheses(难度:Easy)
2017-05-29 16:08
337 查看
算法设计与分析(14)
题目:Valid Parentheses
问题描述: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.
算法思路:
问题为求括号的组合形式是否有效,注意这里使用动态规划并不是一个好的方法。因为当你需要把这个问题划分为多个小问题的时候,你会遇到划分的麻烦。例如,”(([]){})()”, 因为头一个为”(“,找一个”)”作为划分时会遇到问题。想要求解需要遍历所有的划分情况,这样的效率是很低的。这里可以使用高效的算法,因为每个有效的括号比为一对的,所以我们使用stack栈的方式。我们遍历整个字符串:
(1)当括号为”(“或”{“或”[“时,把其放入栈中。
(2)当括号为”)”或”}”或”]”时,若组合的形式是有效的,那么栈中的top必然是对应的左括号,可以把对应的左括号push出来。若不是或者栈为空,那么肯定是无效的。
(3)当已经遍历完的整个字符串,若栈为空,那么该组合有效,否则无效。
实现代码:
#include<iostream> #include<string> #include<stack> #include<map> using namespace std; bool isValid(string s) { stack<char> sta; map<char, char> cmap; cmap[')'] = '('; cmap[']'] = '['; cmap['}'] = '{'; for (int i = 0; i < s.length(); ++i) { if (s[i] == '(' || s[i] == '{' || s[i] == '[') sta.push(s[i]); else if (!sta.empty() && cmap[s[i]] == sta.top()) sta.pop(); else return false; } return sta.empty(); } int main() { string s = ")"; cout << isValid(s) << endl; return 0; }
相关文章推荐
- Easy-题目47:20. Valid Parentheses
- 算法设计与分析(15) -- Generate Parentheses(难度:Medium)
- leetcode_20_Valid Parentheses (easy)
- 【Leetcode-easy】Valid Parentheses
- 20. Valid Parentheses [easy] (Python)
- 20.Valid Parentheses(Stack-Easy)
- LeetCode_Easy心得:20. Valid Parentheses(C语言)
- Leetcode题解14 20. Valid Parentheses
- LeetCode-Easy刷题(5) Valid Parentheses
- Easy 20题 Valid Parentheses
- 【Leetcode-Easy-20】 Valid Parentheses
- leetcode题解-13. Roman to Integer && 14. Longest Common Prefix && 20. Valid Parentheses
- LeetCode OJ 20 Valid Parentheses [Easy]
- LeetCode (Easy Part) Valid Parentheses
- LeetCode-20-Valid Parentheses(堆栈)-Easy
- 蜗牛慢慢爬 LeetCode 20. Valid Parentheses [Difficulty: Easy]
- [Leetcode 20, Easy] Valid Parentheses
- 20. Valid Parentheses (Easy)
- Leetcode 20. Valid Parentheses (Easy) (cpp)
- Valid Parentheses (EASY)