package com.app.main.LeetCode;
/**
* Created with IDEA
* author:Dingsheng Huang
* Date:2019/6/28
* Time:下午8:19
*/
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
/**
* Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
* determine if the input string is valid.
*
* An input string is valid if:
*
* Open brackets must be closed by the same type of brackets.
* Open brackets must be closed in the correct order.
* Note that an empty string is also considered valid.
*
* Example 1:
*
* Input: "()"
* Output: true
* Example 2:
*
* Input: "()[]{}"
* Output: true
* Example 3:
*
* Input: "(]"
* Output: false
* Example 4:
*
* Input: "([)]"
* Output: false
* Example 5:
*
* Input: "{[]}"
* Output: true
*/
public class ValidParentheses {
/**
* 思路: 用栈模拟符号匹配
* @param s
* @return
*/
public boolean isValid(String s) {
Map<String, String> map = new HashMap<>();
map.put("(", ")");
map.put("[", "]");
map.put("{", "}");
Stack<String> stack = new Stack();
// 遍历字符串
for (int i = 0; i < s.length(); i++) {
String item = String.valueOf(s.charAt(i));
// 当前字符属于“左”括号类型,则入栈
if (map.containsKey(item)) {
stack.push(item);
} else {
// 当前字符属于 "右" 括号类型,则判断如果是第一个字符,则必定不合法。
if (stack.empty()) {
return false;
}
// 取栈顶字符"右"括号匹配,匹配不上,则不合法
String popItem = stack.pop();
if (!map.get(popItem).equals(item)) {
return false;
}
}
}
// 遍历完字符串、且栈为空,则合法
return stack.empty();
}
}