京东笔试第一题括号没时间做,师弟的答案
import java.util.*; public class Main { static Map<List<String>, Integer> mapSeqNum=new HashMap<List<String>, Integer>(); public static void main(String[] args) { // TODO 自动生成的方法存根 Scanner in = new Scanner(System.in ); String str=in.next(); while (str!=null){ int num=count(new ArrayList<String>(Arrays.asList(str.split(""))).subList(1,str.length()+1)); System.out.println(num); //System.out.println(new ArrayList<String>(Arrays.asList(str.split(""))).subList(1,str.length()+1)); str=in.next(); } in.close(); // System.out.println(isTrue(Arrays.asList(str.split("")))); } public static int count(List<String> seq) { if(mapSeqNum.containsKey(seq)){ return mapSeqNum.get(seq); } if (seq.size()==2 && seq.get(0).equals("(") && seq.get(1).equals(")")) { return 1; }else { int numSum=0; String str0=seq.get(0); seq.remove(0); for (int i = 0; i < seq.size(); i++) { String str1=seq.get(i); if (str1.equals(")")) { seq.remove(i); //System.out.println(isTrue(seq)); if(isTrue(seq)){ numSum+=count(seq); } seq.add(i, str1); } } seq.add(0, str0); mapSeqNum.put(seq, numSum); return numSum; } } public static boolean isTrue(List<String> tmpseq) { List<String> seq=new ArrayList<String>(tmpseq); // while (seq.size()>0) { for (int i = seq.size()-1; i >=0; i--) { if(seq.get(i).equals("(")){ if(i<seq.size()-1 && seq.get(i+1).equals(")")){ seq.remove(i+1); seq.remove(i); //System.out.println(seq); // break; }else { return false; } } } if(seq.size()==0){ return true; }else { return false; } // } // return true; } }
师弟解决的,惭愧惭愧。没有在线测试,考试结束后完成的。有问题欢迎指正。