zoukankan      html  css  js  c++  java
  • Valid Parentheses

    1. Problem

    一个字符串只能包含 '('')''{''}''[' 和 ']',判断字符串是否是闭合有效字符串。

    Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
    
    The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

    2. Solution

    用字符串数组来模拟栈

     1 public class Solution {
     2     public boolean isValid( String s ){
     3         int len = s.length();
     4         if( len % 2 != 0 )
     5             return false;
     6         char[] left = new char[len];
     7         int count = -1;
     8         for( int i=0; i<len; i++ ){
     9             char curr = s.charAt(i);
    10             if( curr=='(' || curr=='{' || curr=='['  )
    11                 left[++count] = s.charAt(i);
    12             else{
    13                 if( count>=0 && ( left[count] == curr-2 || left[count] == curr-1 ) )
    14                     count--;
    15                 else return false;
    16             }        
    17         }
    18         if( count>=0 )
    19             return false;
    20         return true;
    21     }
    22 }
  • 相关阅读:
    升级系统引起的
    php curl批处理
    看《黑炮事件》想到的
    查找单链表的倒数第k个值
    python绘制树枝
    暑假第九测
    网络流24题(持续更新)
    P2657 [SCOI2009]windy数
    P3177 [HAOI2015]树上染色
    暑假第六测
  • 原文地址:https://www.cnblogs.com/hf-cherish/p/4668785.html
Copyright © 2011-2022 走看看