题目:
给定一个只包括 ‘(‘,’)’,’{‘,’}’,’[‘,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "(]"
输出: false
示例 4:
输入: "([)]"
输出: false
示例 5:
输入: "{[]}"
输出: true
题目地址:https://leetcode-cn.com/problems/valid-parentheses/description/
这道题主要是考验栈的应用,分析起来也很简单,当输入的是 ‘(’ 、’{’ 、’[’ 时候直接入栈,若是 ‘)’ 、’}’ 、’]’ 时候直接移除栈顶元素,判断是 ‘)’ 、’}’ 、’]’ 中的哪一个元素,比如:是 ‘)’ 时候判断当前是否为 ‘)’ 且移除的栈顶元素不等于 ‘(’ ,此时返回false。
代码:
import java.util.Scanner;
import java.util.Stack;
/**
* Created by: HuangFuBin
* Date: 2018/7/22
* Time: 12:54
* Such description: 栈括号匹配应用 https://leetcode-cn.com/problems/valid-parentheses/description/
*/
public class ParenthesisMatching {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0 ; i < s.length() ; i ++){
char c = s.charAt(i);
if(c == '(' || c == '{' || c == '['){
//入栈
stack.push(c);
}else {
if (stack.isEmpty())
return false;
//移除栈顶
char topChar = stack.pop();
if(c ==')' && topChar != '(')
return false;
if(c =='}' && topChar != '{')
return false;
if(c ==']' && topChar != '[')
return false;
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
ParenthesisMatching solution = new ParenthesisMatching();
System.out.println(solution.isValid(s));
}
}
测试:
输入 ()[]{}
打印 true