zoukankan      html  css  js  c++  java
  • 括号字符串有效性验证

    题目:

          

    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.

    思路:

        考察栈的概念,当遇到'(','[','{',时全部入栈,当遇到')',']','}'时,与栈顶元素进行匹配

     1     public static boolean isValid(String s) {
     2         Stack<Character> stack = new Stack<Character>(); 
     3         
     4         if(s != null && s.length() != 0){
     5             char[] charArray = s.toCharArray();
     6             for(char c : charArray){
     7                 if(c == '(' || c == '[' || c == '{'){
     8                     stack.push(c);
     9                 }else if(c == ')' || c == ']' || c == '}'){
    10                     if(stack.empty())
    11                         return false;
    12                     else{
    13                         char temp = stack.pop();
    14                         int val = c - temp;
    15                         if(!(val == 1 || val == 2)){//匹配括号的字符数值差值只有1和2两种可能
    16                             return false;
    17                         }
    18                             
    19                     }
    20                 }else{
    21                     return false;
    22                 }
    23             }
    24         }else
    25             return false;
    26         if(stack.isEmpty())
    27            return true;
    28         else
    29             return false;
    30     }
  • 相关阅读:
    6、加法算术
    5、找出最大和最小的数
    4、计算并输出圆的面积和周长
    2、函数y=f(x)
    1、两数的平方和
    单片机中断寄存器知识点总结
    创建PCB原理图的模板
    电机知识
    结合实例谈谈航拍全景的方法和技巧
    航拍技巧
  • 原文地址:https://www.cnblogs.com/music180/p/6086621.html
Copyright © 2011-2022 走看看