zoukankan      html  css  js  c++  java
  • [leetcode]20. Valid Parentheses有效括号序列

    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
    
    

    题意:

    给定一个括号序列,判断其是否合法。

    思路:

    指针i来扫给定字符串

    对于字符串的每个char,若是左括号,入栈

                                     若栈不为空&&栈顶元素与对应位置的右括号匹配,出栈

    代码:

     1 class Solution {
     2     public boolean isValid(String s) {
     3         Stack<Character> stack = new Stack<>();
     4         for(int i = 0; i<s.length(); i++){
     5             char c = s.charAt(i);
     6             if(c == '(' || c =='{' || c=='['){
     7                 stack.push(c);
     8             }
     9             else if( c == ')' && !stack.empty() && stack.peek() =='('){
    10                 stack.pop();
    11             }
    12             else if( c == '}' && !stack.empty() && stack.peek() =='{'){
    13                 stack.pop();
    14             }
    15             else if( c == ']' && !stack.empty() && stack.peek() =='['){
    16                 stack.pop();
    17             }
    18             else{
    19                 return false;
    20             }
    21         }
    22         return stack.isEmpty();
    23     }
    24 }

    followup:  Valid Parentheses 简化版:只有()一种括号,且input string里有别的字母,加减号。看括号是否是闭合。

    )()()() ----> true
    (+1^$#)(#$) ----> true
    )( ----->false
    (()#%33 ----->false

    代码:

     1 public class valid_parenthese_modified {
     2     public boolean isValid(String s) {
     3         int count = 0;
     4         for (char c : s.toCharArray()) {
     5             if (c == '(')
     6                 count++;
     7             else if (c == ')') {
     8                 if (count == 0) // notes for the if-judge here
     9                     return false;
    10                 count--;
    11             }
    12         }
    13         return count == 0;
    14     }
    15 }
  • 相关阅读:
    zabbix邮件报警设置(加密)
    Linux实战(10):ssh密码被拒绝
    Linux实战(9):Docker一键搭建kms服务
    Linux实战(8):查看文件大小
    Linux实战(7):centos7安装xrdp
    Linux实战(6):Centos8上传镜像
    Linux实战(5):Centos8安装python
    Linux实战(4):Centos7升级python
    nginx实战(1):宝塔设置反向代理
    Dell服务器R710修改iDRAC密码
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9125299.html
Copyright © 2011-2022 走看看