zoukankan      html  css  js  c++  java
  • 2016去哪儿编程题:表达式合法判断

    题目描述

    写一段代码,判断一个包括'{','[','(',')',']','}'的表达式是否合法(注意看样例的合法规则。)

    给定一个表达式A,请返回一个bool值,代表它是否合法。

    测试样例
    "[a+b*(5-4)]*{x+b+b*({1+2)}}"
    返回:true
    测试样例
    "[a+b*(5-4)]*{x+b+b*(({1+2)}}"
    返回:false
    解题
    不考虑左右括号是否匹配,不考虑括号内是否由数字,如:2—1+()+{3]*{5) 这样也可以
    import java.util.*;
    
    public class ChkExpression {
        public boolean chkLegal(String A) {
            // write code here
          
            Stack<Character> stack = new Stack<Character>();
            HashMap<Character,Character> map = new HashMap<Character,Character>();
            map.put('[',']');
            map.put('{','}');
            map.put('(',')');
            for(int i =0;i<A.length();i++){
                char ch = A.charAt(i);
                if(map.containsKey(ch)){
                    stack.push(ch);
                }else if(map.containsValue(ch)){
                    if(stack.isEmpty())
                        return false;
                    char top = stack.peek();
                   // if(map.get(top).equals(ch)){
                        stack.pop();
                   // }else{
                    //    return false;
                    //}
                }
            }
            return stack.isEmpty();
        }
    }

    上面注释去除测试不过

    这个题目好奇怪,竟然不需要考虑括号内是否有数字的情况,所有开始我考虑情况比较多,就不知道怎么做了,讨论中就是按照上面写的



  • 相关阅读:
    CF995A Tesla
    CF961D Pair Of Lines
    P1186 玛丽卡
    CF986B Petr and Permutations
    hdu6331 Problem M. Walking Plan
    Edison UVALive3488
    Be a Smart Raftsman SGU475
    100198H Royal Federation
    100197G Robbers
    Evil Book -- CodeChef
  • 原文地址:https://www.cnblogs.com/theskulls/p/5338755.html
Copyright © 2011-2022 走看看