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 }
  • 相关阅读:
    浅谈页面中的焦点
    简单的jQuery幻灯片实现
    从is(":checked")说起
    通过Javascript得到URL中的参数(query string)
    Javascript设置对象属性为"只读"
    Javascript判断两个日期是否相等
    利用HttpWebRequest访问WebApi
    利用Newtonsoft.Json实现Json序列化与反序列化
    在ASP.NET MVC中以post方式传递数组参数的示例
    SQL Server 锁表、查询被锁表、解锁相关语句
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9125299.html
Copyright © 2011-2022 走看看