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.

    The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

    题意:返回这些括号的使用是否正确:

    思路:碰到前括号,存入栈,碰到后括号,当和前括号对应的时候,前括号出栈,否则返回错误,最后栈底元素为0的话,返回正确

     1 bool isValid(char* s) {
     2     int flag[200]={0};
     3     int i=0,j=0;
     4     int c;
     5     while(s[i])
     6         {
     7            if('('==s[i]) c=-1;
     8            else if(')'==s[i]) c=1;
     9            else if('{'==s[i]) c=-2;
    10            else if('}'==s[i]) c=2;
    11            else if('['==s[i]) c=-4;
    12            else if(']'==s[i]) c=4;
    13            if((c<0&&0==j)||(flag[j-1]<0&&c<0)) //前括号,入栈
    14                 {
    15                     flag[j]=c;
    16                     j++;
    17                 }
    18                 else if(!(c+flag[j-1])) //对应的后括号,出栈
    19                 {
    20                     j--;
    21                     flag[j]=0;
    22                 }
    23                 else                                     //其他,返回错误
    24                     return false;
    25             i++;
    26         }
    27         if(!flag[0])
    28             return true;   
    29             else 
    30             return false;
    31         
    32 }        

     Python :

     1 class Solution(object):
     2     def isValid(self, s):
     3         """
     4         :type s: str
     5         :rtype: bool
     6         """
     7         pre = {'(':-1,'[':-2,'{':-4}
     8         aft = {')':1,']':2,'}':4}
     9         stk = []
    10         for item in s:
    11             if item in pre:
    12                 stk.append(item)
    13             if item in aft:
    14                 if not len(stk):
    15                     return False
    16                 if pre[stk.pop()]+aft[item]:
    17                     return False
    18         return False if len(stk) else True
  • 相关阅读:
    UVA 10970 Big Chocolate
    HBuilder 安装uviewui2.0
    域名访问配置支持ipv6
    SSIS学习视频(SQL Server 2008)
    碰到MySQL无法启动1067错误问题
    对存储过程进行加密和解密(SQL 2008/SQL 2012)
    脚本文件比较工具WinMerge
    通过SQL绘制杨辉三角
    通用分页存储过程(SQL Server 2005)
    重新组织和重新生成索引sp_RefreshIndex
  • 原文地址:https://www.cnblogs.com/fcyworld/p/6154990.html
Copyright © 2011-2022 走看看