leetCode/src/main/java/com/leetcode/string/IsValidKuoHao.java

63 lines
1.7 KiB
Java
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.leetcode.string;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
/**
* 给定一个只包括 '('')''{''}''['']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
来源力扣LeetCode
链接https://leetcode-cn.com/problems/valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class IsValidKuoHao {
private static Map<Character, Character> kuohao = new HashMap<Character, Character>() {
/**
*
*/
private static final long serialVersionUID = 1L;
{
put('(', ')');
put('{', '}');
put('[', ']');
}};
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (stack.empty()) {
stack.push(c);
continue;
}
Character pre = stack.peek();
if (pre == null || kuohao.get(pre) == null) {
stack.push(c);
continue;
}
if (kuohao.get(pre) == c) {
stack.pop();
} else {
stack.push(c);
}
}
return stack.empty();
}
public static void main(String[] args) {
IsValidKuoHao validKuoHao = new IsValidKuoHao();
String str = "{[]}";
boolean isValid = validKuoHao.isValid(str);
System.out.println(isValid);
}
}