Leetcode-20:Valid Parentheses
2017-07-26 23:19
351 查看
Question:
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.
给定一个字符串只包含字符“(”、“)”、“{”、“}”,“[”和“]”,判断输入的字符串是有效的。
括弧必须以正确的顺序关闭,“()”和“()[ ] { }”都是有效的但”(]”和“([)]”不是。
Answer:
使用栈来做。
当是左半边括弧的时候入栈,右半边括弧的时候栈顶元素出栈,判断此时栈顶元素是否和字符串此次括弧对应,对应则顺利出栈,不对应则返回false。字符串遍历完成后栈为空时返回true,非空时返回false。
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.
给定一个字符串只包含字符“(”、“)”、“{”、“}”,“[”和“]”,判断输入的字符串是有效的。
括弧必须以正确的顺序关闭,“()”和“()[ ] { }”都是有效的但”(]”和“([)]”不是。
Answer:
使用栈来做。
当是左半边括弧的时候入栈,右半边括弧的时候栈顶元素出栈,判断此时栈顶元素是否和字符串此次括弧对应,对应则顺利出栈,不对应则返回false。字符串遍历完成后栈为空时返回true,非空时返回false。
import java.util.Stack; public class Solution { public boolean isValid(String s){ Stack<Character> stack = new Stack<Character>(); int x = 0; for(x=0;x<s.length();x++){ if(s.charAt(x)=='(' || s.charAt(x)=='[' || s.charAt(x)=='{'){ stack.push(s.charAt(x)); } if(s.charAt(x)==')'){ if(stack.empty()) return false; char ch = stack.pop(); if(ch=='(') continue; else return false; } else if(s.charAt(x)==']'){ if(stack.empty()) return false; char ch = stack.pop(); if(ch=='[') continue; else return false; } else if(s.charAt(x)=='}'){ if(stack.empty()) return false; char ch = stack.pop(); if(ch=='{') continue; else return false; } } if(stack.empty()){ return true; } else return false; } }
相关文章推荐
- LeetCode 20. Valid Parentheses(括号校验)
- Leetcode[20]-Valid Parentheses
- Leetcode - 20. Valid Parentheses
- Leetcode刷题记——20. Valid Parentheses (有效的括号即括号匹配)
- leetcode 20|22|32. Valid Parentheses 22. Generate Parentheses 32. Longest Valid Parentheses
- leetcode题解-13. Roman to Integer && 14. Longest Common Prefix && 20. Valid Parentheses
- LeetCode 20: Valid Parentheses
- LeetCode之20---Valid Parentheses
- LeetCode20 - Valid parentheses
- 【leetcode】20. Valid Parentheses
- 【LeetCode】20 - Valid Parentheses
- [Leetcode] 20. Valid Parentheses
- 个人记录-LeetCode 20. Valid Parentheses
- LeetCode --- 20. Valid Parentheses
- [LeetCode]20. Valid Parentheses
- leetcode (20) - Valid Parentheses
- <LeetCode OJ>Valid Parentheses【20】
- Leetcode 20 Valid Parentheses
- leetcode 20. Valid Parentheses
- leetCode 20.Valid Parentheses (有效的括号) 解题思路和方法