• [Leetcode 20] 20 Valid Parentheses


    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.

    Analysis:

    Use a stack to help. If the element is '(', '[', '{', push it onto stack. If the element is ')', ']', '}', pop one element from stack and see if they match with each other. If not match, then return false;

    Other cases may cause false result are: 1.  Meet with ')', ']', '}', but the stack is empty; 2. The string has been processed, but the stack is not empty.

    The time complexity is O(n), the space complexity is O(n) in worst case, O(1) in best case; 

    Code:

     1 public class Solution {
     2     public boolean isValid(String s) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         char[] stack = new char[100];
     6         int tos = 0;
     7         char tmp;
     8         
     9         for (int i=0; i<s.length(); ++i) {
    10             tmp = s.charAt(i);
    11             switch(tmp) {
    12                 case '(': case '[': case '{': stack[tos++] = tmp; break;
    13                 case ')': 
    14                     if (tos==0 || stack[--tos]!='(') 
    15                             return false;
    16                     break;
    17                 case '}': 
    18                     if (tos==0 || stack[--tos]!='{') 
    19                             return false;
    20                     break;    
    21                 case ']': 
    22                     if (tos==0 || stack[--tos]!='[') 
    23                         return false;
    24                     break;
    25             }
    26         }
    27      
    28         if (tos != 0)
    29             return false;
    30         else
    31             return true;
    32     }
    33 }
    View Code

    Attention:

  • 相关阅读:
    特别记录:OMNET神坑
    OMNet++运行项目后,出现错误:out/clang-release//DynaPacket_m.o:(.text+0x1296): 跟着更多未定义的参考到 _Unwind_Resume
    【2021年1月4日】与父谈话总结
    Ceph架构和原理
    Mysql的InnoDB存储引擎锁机制
    MySQL 分区表
    MySQL日志之binlog、redo log、undo log
    PTA刷题记录
    [POI2015]MYJ
    Manacher初步
  • 原文地址:https://www.cnblogs.com/freeneng/p/3086476.html
Copyright © 2020-2023  润新知