/**
* 阿里面试题
* 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