阿里面试算法题 :

/**
 * 阿里面试题
 *    Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
 * 1. Open brackets must be closed by the same type of brackets.
 * 2. Open brackets must be closed in the correct order.
 * Note that an empty string is also considered valid.
 */

阿里一面通过,然后第二天二面,第二天大早上我还在梦乡,突然一个电话打来让我写一道算法体,此时的我还有点晕,再加上心里有点紧张,当时写的比较麻烦,感觉没有通过。晚上吃完饭,坐到电脑前面心平气和,再看这道题突然一个完美的解决方案在我的脑海:下面是我的解决方案:

/**
 * 阿里面试题
 *    Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
 * 1. Open brackets must be closed by the same type of brackets.
 * 2. Open brackets must be closed in the correct order.
 * Note that an empty string is also considered valid.
 */
public class AliArith {

    static Map<String,String> map = new HashMap<String,String>();
    static{
        map.put("(",")");
        map.put("[","]");
        map.put("{","}");
    }

    private static String opend=  "({[";
    private static String close = ")}]";

    /**
     * () true
     * (] false
     * ()[]{}  true
     * {()}  true
     *
     *
      * @param str
     * @return
     */

    public static  boolean cheched(String str){
        if(str ==null || str.length() == 1){
            return false;
        }else if("".equals(str.trim())){
           return true;
        }
        else if(str.length() % 2==0) {
            String[] split = str.split("");
            ArrayList<String> arrayList = new ArrayList<>();//从左向右遍历 记录开
            for(String str_ : split){
                //如果是开
                if(opend.contains(str_)){
                    arrayList.add(str_);
                }if(close.contains(str_)){
                    int lastIndex = arrayList.size()-1;
                    String lastOpen = arrayList.get(lastIndex);
                    String getClose = map.get(lastOpen);
                    if(str_.equals(getClose)){// 说明匹配,开始消除
                        arrayList.remove(lastIndex);
                    }else{
                       return false;  
                       }

                }
            }
            //说明被消完,完全匹配
            if(arrayList.size()==0){
                return true;
            }else{
                return false;
            }

        }

        return false;
    }
    
    @Test
    public void test1(){
        boolean cheched = AliArith.cheched("{()[]{}}");
        System.out.println("checked : "+cheched);
    }

}

总结: 在面试的时候一定要保持冷静,但是往往有很多人很难做到,比如我,感谢阿里我会继续努力的

java面试题网站:www.javaoffers.com

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值