Leetcode - Valid Parentheses
来源:互联网 发布:seo在线刷外链工具 编辑:程序博客网 时间:2024/05/22 08:02
问题
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.
答案
#include<stack>class Solution {public: bool isValid(std::string s) { const int ROUND_BRACKET = 1; const int SQU_BRACKET = 2; const int BIG_BRACKET = 3; std::stack<int> Stack; int length = s.length(); bool flag = true; for (int i = 0; i < length; i++){ if (s[i] == '('){ Stack.push(ROUND_BRACKET); } else if (s[i] == '['){ Stack.push(SQU_BRACKET); } else if (s[i] == '{'){ Stack.push(BIG_BRACKET); } else if (s[i] == ')'){ if (!Stack.empty()){ if (Stack.top() != ROUND_BRACKET){ flag = false; break; } else Stack.pop(); } else{ flag = false; break; } } else if (s[i] == ']'){ if (!Stack.empty()){ if (Stack.top() != SQU_BRACKET){ flag = false; break; } else Stack.pop(); } else{ flag = false; break; } } else if (s[i] == '}'){ if (!Stack.empty()){ if (Stack.top() != BIG_BRACKET){ flag = false; break; } else Stack.pop(); } else{ flag = false; break; } } } if (Stack.empty() && flag == true){ flag = true; } else{ flag = false; } return flag;}};
题目分析
题目分析
这个题目就是栈的应用,也就是当遇到左侧括号是入栈,遇到右侧的括号是和栈顶匹配,如果是相同的,那么就出栈,如果是不同的就停止程序然后返回错误值。
在写代码时,要尽量考虑多种情况。例如
[
此时,显然是不匹配的,因此在代码的设计逻辑中,在程序以正确的结果结束时,一定要保证栈是空的。
同时要保证语法正确,即
]
如果只是右侧括号,那么这是程序需要判断栈是否为空,因为初始栈肯定是空栈,所以这个时候不能调用top()来进行对比。
代码分析
这里主要使用了C++里面的栈的特性,当然也可以自己编写一个栈来实现。
0 0
- LeetCode: Valid Parentheses
- LeetCode: Longest Valid Parentheses
- LeetCode: Valid Parentheses
- LeetCode Longest Valid Parentheses
- [Leetcode] Valid Parentheses
- LeetCode: Longest Valid Parentheses
- [Leetcode] Longest Valid Parentheses
- LeetCode : Valid Parentheses
- [leetcode]longest Valid Parentheses(!!)
- Leetcode: Valid Parentheses
- leetcode 52: valid parentheses
- [Leetcode] Longest Valid Parentheses
- leetcode Longest Valid Parentheses
- 【leetcode】Valid Parentheses
- 【leetcode】Longest Valid Parentheses
- [LeetCode]Longest Valid Parentheses
- [LeetCode]Valid Parentheses
- LeetCode-Valid Parentheses
- javascript对象章节学习
- PAT 1013. 数素数
- 数组、结构体、指针3
- 九度 题目1123:采药
- 由一道python的面试题说起
- Leetcode - Valid Parentheses
- Codeforces 519E A and B and Lecture Rooms LCA
- ucgui学习笔记01简介
- 直接拿来用!最火的Android开源项目(一)
- MIME详解
- 驱动开发中应该注意的事项
- IOS程序启动引导示例
- J2EE企业级开发基础教程(2) - Java编程规范
- 直接拿来用!最火的Android开源项目(二)