LeetCode 20. Valid Parentheses--验证括号是否有效
2017-08-25 12:17
726 查看
Given a string containing just the characters
determine if the input string is valid.
The brackets must close in the correct order,
all valid but
not.
'(',
')',
'{',
'}',
'['and
']',
determine if the input string is valid.
The brackets must close in the correct order,
"()"and
"()[]{}"are
all valid but
"(]"and
"([)]"are
not.
import java.util.Stack; public class Main { public boolean isValid(String s) { int n = s.length(); Stack<Character> stack = new Stack<Character>(); char[] c = s.toCharArray(); for (int i = 0; i < n; i++) { if (c[i] == '(') { stack.push(')'); } else if (c[i] == '[') { stack.push(']'); } else if (c[i] == '{') { stack.push('}'); } else if (stack.isEmpty() || stack.pop() != c[i]) {//pop是返回栈顶元素,并且删除栈顶元素 return false; } }//for return stack.isEmpty(); }//isValid public static void main(String[] args) { // System.out.println(new Main().isValid("{[()]}"));//true System.out.println(new Main().isValid("{"));//false } }
相关文章推荐
- leetcode20 Valid Parentheses 有效的括号
- leetcode_java.T020_ValidParentheses 给定一个只包含(‘, ‘)’, ‘{‘, ‘}’, ‘[’ 和‘]’的字符串,验证它是否是有效的。
- 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 Valid Parentheses 有效括号
- leetcode Valid Parentheses 验证括号
- LeetCode Valid Parentheses 有效括号
- [LeetCode] Valid Parentheses 验证括号
- [LeetCode] Valid Parentheses 验证括号
- LeetCode | 32. Longest Valid Parentheses——最长有效括号匹配长度
- LeetCode 20 Valid Parentheses(用栈判断括号匹配)
- 【LeetCode-面试算法经典-Java实现】【032-Longest Valid Parentheses(最长有效括号)】
- leetcode32 Longest Valid Parentheses 最长有效括号序列
- [LeetCode] 32. Longest Valid Parentheses 最长有效括号
- LeetCode 20 Valid Parentheses(括号匹配)