携程3.4号笔试题,有AC全部的可以交流一下
1. 可能因为int转char的过程中会有数据大小的溢出所以只有0.8.的AC public static void getAns(String str) { LinkedList<Character> stack = new LinkedList<>(); LinkedList<Integer> list = new LinkedList<>(); int ans = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == ' ') { continue; } else if (str.charAt(i) == ')') { int res = 0; list.clear(); while (!stack.isEmpty() && stack.peekLast() != '(') { char char1 = stack.pollLast(); if (char1 != '*' && char1 != '-' && char1 != '+') { if (Character.isDigit(char1)) { list.addFirst(Integer.parseInt(char1 + "")); } else { list.addFirst((int) char1); } } else { if (char1 == '*') { res = 1; for (int j = 0; j < list.size(); j++) { res *= list.get(j); } } else if (char1 == '+') { for (int j = 0; j < list.size(); j++) { res += list.get(j); } } else { res = list.get(0); for (int j = 1; j < list.size(); j++) { res -= list.get(j); } } ans = res; } } stack.pollLast(); if (stack.isEmpty()) { System.out.println(ans); } else { stack.offerLast((char) res); } } else { if (Character.isDigit(str.charAt(i))) { String num = ""; for (int x = i; x < str.length(); x++) { if (Character.isDigit(str.charAt(x))) { num = num + str.charAt(x); } else { i = x - 1; break; } } stack.offerLast((char) Integer.parseInt(num)); } else { stack.offerLast(str.charAt(i)); } } } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNextLine()) { String str = sc.nextLine(); if (str.equals("")) { break; } else { getAns(str); } } }2. 这个是后面写的,能跑过测试用例,也可以剪枝来减少运行时间。另外如过有大佬能转成动态规划的话可以贴出来看一下。static ArrayList<List<Integer>> lists=new ArrayList<>(); public static void maxAount(int[] num,int n){ if(num.length<n){ return ; } ArrayList<Integer> list=new ArrayList<>(); set(num,0,n+1,list); int max=0; System.out.println(lists.size()); for(int i=0;i<lists.size();i++){ int min=lists.get(i).get(0); for (Integer integer : lists.get(i)) { if(integer<min){ min=integer; } } if(min>max){ max=min; } } System.out.println(max); } public static void set(int[] num,int start,int n,ArrayList<Integer> list){ if(n<0||start>num.length){ return; } if(n==0&&start==num.length){ lists.add(new ArrayList<Integer>(list)); return ; } int cur=start; for(int i=start;i<num.length;i++){ int sum=0; for(int j=cur;j<=i;j++){ sum=sum+num[j]; } list.add(sum); set(num,i+1,n-1,list); list.remove(list.size()-1); } }
#笔试题目##携程#