给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: “()”
输出: true
示例 2:
输入: “()[]{}”
输出: true
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
import java.util.Map;
import java.util.Stack;
import java.util.HashMap;
class Solution {
public static boolean isValid(String s) {
if ("".equals(s)) {
return true;
}
String[] split = s.split("");
Map<String,String> map =new HashMap<String,String>();
map.put("}", "{");
map.put("]", "[");
map.put(")", "(");
Stack<String> stack = new Stack<>();
for (int i = 0; i < split.length; i++) {
String string = split[i];
if(map.containsValue(string))
{
stack.push(string);
}
if(stack.isEmpty())
{
return false;
}
String peek = stack.peek();
if (map.containsKey(string)) {
if (map.get(string).equals(peek)) {
stack.pop();
}else {
return false;
}
}
}
return stack.isEmpty();
}
}
本文深入探讨了括号匹配的有效性判断算法,通过使用栈和映射表实现了一种高效的方法来验证包含各种括号(如圆括号、方括号和花括号)的字符串是否正确闭合。文章提供了详细的代码示例,并解释了如何处理空字符串等特殊情况。
512

被折叠的 条评论
为什么被折叠?



