[leetcode] 20. Valid Parentheses (easy)

it2025-11-19  10

原题链接

匹配括号思路: 用栈,遍历过程中,匹配的成对出栈;结束后,栈空则对,栈非空则错。 Runtime: 4 ms, faster than 99.94% of Java

class Solution { public boolean isValid(String s) { Stack<Character> sta = new Stack<Character>(); for (int i = 0; i < s.length(); i++) { char temp = s.charAt(i); if (temp == '[' || temp == '(' || temp == '{') { sta.push(temp); } else { if (sta.isEmpty()) return false; char top = ' '; if (temp == ']') top = '['; if (temp == ')') top = '('; if (temp == '}') top = '{'; if (top == sta.peek()) sta.pop(); else return false; } } return sta.isEmpty() ? true : false; } }

转载于:https://www.cnblogs.com/ruoh3kou/p/9951405.html

相关资源:数据结构—成绩单生成器
最新回复(0)