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 }
  • 相关阅读:
    [整] Android Fragment 生命周期图
    LruCache--远程图片获取与本地缓存
    Android基于XMPP Smack openfire 开发的聊天室
    基于XMPP协议的Android即时通信系
    Android实现推送方式解决方案
    日历工具类(一)——公历农历互相转换
    IdHTTPServer使用注意问题
    用TIdIPWatch获取本地IP
    delphi TStringList 用法详解
    WIN7 64位配置X86 MySQL 数据源
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9125299.html
Copyright © 2011-2022 走看看