LeetCode Top 100 Liked Questions 20. Valid Parentheses (Java版; Easy)

welcome to my blog

LeetCode Top 100 Liked Questions 20. Valid Parentheses (Java版; Easy)

题目描述

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

An input string is valid if:

Open brackets must be closed by the same type of brackets.
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
class Solution {
    public boolean isValid(String s) {
        int n = s.length();
        if(n==0){
            return true;
        }
        Stack<Character> stack = new Stack<>();
        stack.push('*');
        for(int i=0; i<n; i++){
            char ch = s.charAt(i);
            if(ch=='(' || ch=='[' ||ch=='{'){
                stack.push(ch);
            }else if(ch==')'){
                char ch2 = stack.pop();
                if(ch2!='('){
                    return false;
                }
            }else if(ch==']'){
                char ch2 = stack.pop();
                if(ch2!='['){
                    return false;
                }
            }else if(ch=='}'){
                char ch2 = stack.pop();
                if(ch2!='{'){
                    return false;
                }
            }
        }
        return stack.size()==1;
    }
}
第一次做, 核心思想:使用一个栈, 只压入括号的左半边, 当遇到括号的右半边时, 如果此括号的右半边和栈顶元素配对, 则弹出栈顶元素, 继续下一轮循环; 如果此括号的右半边和栈顶元素不配对, 则直接返回false; 循环结束后,如果栈中没有元素则返回true, 如果栈中有元素则返回false
  • 自己想到了用栈解决这个问题, 值得鼓励, 虽然是easy级别
import java.util.Stack;
class Solution {
    public boolean isValid(String s) {
        if(s==null || s.length()%2==1)
            return false; //和面试官商量
        if(s.length()==0)
            return true;
        
        //栈中只压括号的左半边
        Stack<Character> stack = new Stack<>();
        char curr;
        for(int i=0; i<s.length(); i++){
            curr = s.charAt(i);
            if(curr=='(' || curr=='[' || curr=='{')
                stack.push(curr);
            else if(!stack.isEmpty() && isMatch(stack.peek(), curr))
                stack.pop();
            else//curr==')'  ']'  '}'但是stack为空或者curr!=stack.peek()
                return false;
        }
        return stack.isEmpty();
    }
    public boolean isMatch(char a, char b){
        if(a=='(')
            return b==')';
        if(a=='[')
            return b==']';
        if(a=='{')
            return b=='}';
        return false;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值