Leetcode014--括号验证匹配
2016-11-15 15:41
309 查看
一、原题
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.
给定一个只包含 '(', ')', '{', '}', '[' and ']', 的字符串,验证它是否是有效的。括号必须配对,并且要以正确的顺序。
比如给出字符串{[(sdffsf)]},我们返回true
建立以个栈,遍历每个元素,当为左括号的时候入栈,为右括号的时候,进行判断和出栈,其他的时候就break,遍历完之后看下栈中是否为空就可以了。
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.
二、中文
给定一个只包含 '(', ')', '{', '}', '[' and ']', 的字符串,验证它是否是有效的。括号必须配对,并且要以正确的顺序。
三、举例
比如给出字符串{[(sdffsf)]},我们返回true
四、思路
建立以个栈,遍历每个元素,当为左括号的时候入栈,为右括号的时候,进行判断和出栈,其他的时候就break,遍历完之后看下栈中是否为空就可以了。
五、程序
package LeetCode; import java.util.Stack; public class Leetcode015 { public static void main(String args[]){ System.out.println(isValid("{([]){())(()}}")); System.out.println(isValid("({qr[wafd]})")); } public static boolean isValid(String s) { Stack<Character> stack = new Stack<Character>(); int index = 0; Character top; while (index < s.length()) { Character c = s.charAt(index); //当为这三个符号的时候就 switch (c) { case '(': case '[': case '{': stack.push(c); break; case ')': if (stack.isEmpty()) { return false; } top = stack.lastElement(); if (top == '(') { stack.pop(); } else if (top == '[' || top == '{') { return false; } else { stack.push(c); } break; case ']': if (stack.isEmpty()) { return false; } top = stack.lastElement(); if (top == '[') { stack.pop(); } else if (top == '(' || top == '{') { return false; } else { stack.push(c); } break; case '}': if (stack.isEmpty()) { return false; } top = stack.lastElement(); if (top == '{') { stack.pop(); } else if (top == '[' || top == '(') { return false; } else { stack.push(c); } break; //其他的情况也就是当时一下字母的时候就跳过 default: break; } index++; } return stack.isEmpty(); } }---------------------output----------------------
false true
相关文章推荐
- 栈验证表达式中的括号是否匹配
- Longest Valid Parentheses(最长的括号匹配)【面试算法leetcode】
- LeetCode 20 Valid Parentheses 括号匹配问题
- LeetCode 32 Longest Valid Parentheses 最大合法括号匹配长度计算 动态规划算法有待学习
- 【LeetCode-面试算法经典-Java实现】【020-Valid Parentheses(括号验证)】
- 验证括号匹配-算法
- 网易2016年Java工程师实习编程题目之括号匹配的验证
- [LeetCode] Valid Parentheses 验证括号
- 验证花括号的匹配
- LeetCode Longest Valid Parentheses 括号匹配
- leetcode 括号匹配系列
- LeetCode | Valid Parentheses(括号匹配)
- [LeetCode]—Longest Valid Parentheses 最长括号匹配
- leetcode 括号匹配
- 验证花括号成对匹配
- Generate Parentheses (括号匹配)【leetcode】
- leetcode题解:Valid Parentheses(栈的应用-括号匹配)
- 【leetcode】括号符匹配问题(Parentheses):Valid Parentheses|Generate Parentheses|LongestValid Parentheses
- leetcode 20 Valid Parentheses 括号匹配
- 验证括号是否匹配