Valid Parentheses Easy
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.
public boolean isValid(String s) { Map<Character, Character> pM = new HashMap<Character, Character>(); pM.put('(', ')'); pM.put('{', '}'); pM.put('[', ']'); Stack<Character> pS = new Stack<Character>(); for (Character c : s.toCharArray()) { if (pM.containsKey(c)) { pS.push(pM.get(c)); } else { if (pS.isEmpty() || c != pS.pop()) return false; } } return pS.isEmpty(); }
思路:典型的压栈出栈操作,遇左括号则压右括号,右则出栈且对比。对比有不同或最后栈不为空,则失败。
本文深入探讨了括号匹配的有效算法,通过使用栈结构来判断字符串中的括号是否正确闭合。介绍了如何利用哈希映射存储括号对,以及栈的压入和弹出操作确保括号顺序正确。
1620

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



