阅读 50

LeetCode-20.Valid Parentheses

Title Description

20. Valid Parentheses

Given a string s 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.

给定一个只包括 ‘(‘,‘)‘,‘{‘,‘}‘,‘[‘,‘]‘ 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

  • 左括号必须用相同类型的右括号闭合。
  • 左括号必须以正确的顺序闭合。
import java.util.Stack;
class Solution {
    public boolean isValid(String s) {
      //jdk util包下的stack。泛型内写入的是char的包装类
        Stack stack = new Stack<>();
      
      //for循环进行遍历
        for(int i = 0; i < s.length();i++){
          //通过charAt 将遍历到的括号存放在 c 中
            char c = s.charAt(i);
          //判断 如果c是 ([{  这三个的一种,那么进行push操作 放到栈的底部
            if(c == ‘(‘ || c == ‘[‘ ||  c == ‘{‘){
                stack.push(c);
            }else{
              	// 否则 首先判断stack是不是有东西
                if(stack.isEmpty()){
                    return false;
                }
              //定义topChar 存放的为栈顶
                char topChar = stack.pop();
              //此时如果c等于右括号,那么判断栈顶的topChar是否为左括号
                if(c == ‘)‘ && topChar != ‘(‘){
                    return false;
                }
                if(c == ‘]‘ && topChar != ‘[‘){
                    return false;
                }
                if(c == ‘}‘ && topChar != ‘{‘){
                    return false;
                }
            }
        }
      //最终判断stack是否还有内容
        return stack.isEmpty();
    }
}

原文:https://www.cnblogs.com/pengcode/p/15311807.html

文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐