149.Valid Parentheses(有效的括号)

本文介绍了一种利用栈数据结构来验证括号字符串有效性的算法。通过两个不同风格的Java实现,展示了如何确保括号正确闭合且类型一致。文章还提供了一个简洁版的解决方案,便于理解与应用。

题目:

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

给定一个只包含字符'(',')','{','}','['和']'的字符串,确定输入字符串是否有效。

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.必须使用相同类型的括号关闭左括号。
  2. 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

解答:

自己写的:

 1 class Solution {
 2     public boolean isValid(String s) {
 3         if(s==null || s.length()==0) return true;
 4         Stack<Character> stack=new Stack<>();
 5         for(int i=0;i<s.length();i++){
 6             if(s.charAt(i)=='(' || s.charAt(i)=='[' || s.charAt(i)=='{'){
 7                 stack.push(s.charAt(i));
 8             }else if(s.charAt(i)==')' || s.charAt(i)==']' || s.charAt(i)=='}'){
 9                 if(stack.isEmpty()){
10                     return false;
11                 }else{
12                     char c=stack.peek();
13                     char b=match(c);
14                     if(b==s.charAt(i))
15                         stack.pop();
16                     else
17                         return false;
18                 }
19             }
20         }
21         return stack.isEmpty();
22     }
23     
24     private char match(Character c){
25         char res;
26         if(c=='(')
27             res=')';
28         else if(c=='[')
29             res=']';
30         else
31             res='}';
32         return res;
33     }
34 }

简洁:

 1 class Solution {
 2     public boolean isValid(String s) {
 3         Stack<Character> stack=new Stack<>();
 4         for(char c:s.toCharArray()){
 5             if(c=='(')
 6                 stack.push(')');
 7             else if(c=='[')
 8                 stack.push(']');
 9             else if(c=='{')
10                 stack.push('}');
11             else if(stack.isEmpty() || stack.pop()!=c)
12                 return false;
13         }
14         return stack.isEmpty();
15     }
16 }

详解:

典型的用栈实现的问题

转载于:https://www.cnblogs.com/chanaichao/p/9613063.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值