猿辅导笔试
猿辅导选择题,难到爆炸!
1.有序的数组,任意交换两个元素,希望你把元素给找出来。
package Yuan; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(sc.hasNextLine()){ String line = sc.nextLine(); String[] split = line.split(" "); int[] arr = new int[split.length]; for(int i = 0;i<arr.length;i++){ arr[i] = Integer.parseInt(split[i]); } int[] number = findNumber(arr); System.out.println(number[0] + number[1]); } } private static int[] findNumber(int[] arr) { int[] res = new int[2]; int temp1 = -1; int temp2 = -1; int n = arr.length-1; int i; for(i = 0;i<n;i++){ if(arr[i+1] < arr[i]){ temp2 = i+1; if(temp1 == -1){ temp1 = i; }else{ break; } } } res[0] = temp1+1; res[1] = temp2+1; return res; } }
2.给定字符串让你求一共有多少个括号,[]代表一个括号,[]2代表两个括号,[][]2代表3个括号,[[]2]3代表9个括号(有三个括号,每个括号内有两个小括号),[[][]2]3代表12个括号。以此类推。
与LC856类似。
这里参考了大佬的代码,我没AC,难受!
package Yuan; import java.util.Scanner; import java.util.Stack; public class Mains_2 { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s = in.nextLine(); System.out.println(getRes(s)); //[][[][][]2]3 16 //[][][[[]3[]2]2]2 28 } public static int getRes(String s) { Stack<Integer> stack = new Stack<>(); char[] arr = s.toCharArray(); for (int i = 0; i < arr.length; i++) { if (arr[i] == '[') { stack.push(0); } else { if (stack.peek() == 0) { int t = 0; while (i + 1 < arr.length && arr[i + 1] != '[' && arr[i + 1] != ']') { i++; t = t * 10 + Integer.parseInt(String.valueOf(arr[i])); } if (t == 0) t = 1; stack.pop(); stack.add(t); } else { int inScore = 0; while (stack.peek() != 0) { inScore += stack.peek(); stack.pop(); } stack.pop(); int t = 0; while (i + 1 < arr.length && arr[i + 1] != '[' && arr[i + 1] != ']') { i++; t = t * 10 + Integer.parseInt(String.valueOf(arr[i])); } stack.add((inScore + 1) * t); } } } int res = 0; while (!stack.empty()) { res += stack.pop(); } return res; } }
3.