keep Java 开发工程师(2020 年校招)
第一题AC 100%
坑:
String[] s1 = str1.substring(1, str1.length() - 1).split(","); String[] s2 = str2.substring(1, str2.length() - 1).split(",");如果输入语句如同上面处理,只能AC60%,报错数组越界
改正,
想法一:发现数组越界,想到可能字符串的长度可能很长,想着将输入的字符串分割后用arraylist来存储。
嗯忙活了很久,发现行不通
想法二:猜测可能输入的字符串中间有空格。
添加replace(" ","") 替换到输入的字符串中的空格,AC100%
String[] s1 = str1.substring(1, str1.length() - 1).replace(" ", "").split(","); String[] s2 = str2.substring(1, str2.length() - 1).replace(" ", "").split(",");
package middleLinkCode; import java.util.Scanner; public class keep1 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); String str1 = sc.nextLine(); String str2 = sc.nextLine(); String[] s1 = str1.substring(1, str1.length() - 1).replace(" ", "").split(","); String[] s2 = str2.substring(1, str2.length() - 1).replace(" ", "").split(","); int[] arr1 = new int[s1.length]; int[] arr2 = new int[s2.length]; for (int i = 0; i < s1.length; i++) arr1[i] = Integer.valueOf(s1[i]); for (int i = 0; i < s2.length; i++) arr2[i] = Integer.valueOf(s2[i]); System.out.println(cal(arr1, arr2)); sc.close(); } private static int cal(int[] water, int[] cost) { // TODO Auto-generated method stub if (water == null || water.length == 0 || cost == null || cost.length == 0) return -1; int sum = 0, total = 0, temp = 0; for (int i = 0; i < water.length; i++) { int count = water[i] - cost[i]; sum += count; total += count; if (sum < 0) { sum = 0; temp = i + 1; } } if (total >= 0) return temp; else return -1; } }
第二题 不会
第三题
坑1:反转后最后一个单词后面没有空格
可以如下操作
package middleLinkCode; import java.util.Scanner; public class keep3 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); String[] str = sc.nextLine().split(" "); StringBuffer sb = new StringBuffer(); for (int i = str.length - 1; i >= 0; i--) if (i == 0) sb.append(str[i]); else sb.append(str[i] + " "); System.out.println(sb.toString()); sc.close(); } }或者加个trim();
for (int i = str.length - 1; i >= 0; i--) sb.append(str[i] + " "); System.out.println(sb.toString().trim());总结,题目不难。但是如果很少做过笔试题的同学,其实很难意识到,考题会在什么地方设置障碍。
所以
对于把输入的东西当成字符串来处理的时候,碰壁后,可以想想输入的字符串中空格是否处理,或者中间可能会存在多个空格。
其实很多公司都会这样设坑,比如vipkid等等
public class vipkid1 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); String str = sc.nextLine(); //下面这个语句很重要哦 String string = str.replace(" ", "");//这个语句很重要哦 //上面这个语句很重要哦 String[] temp = string.split(","); int[] arr = new int[temp.length]; for (int i = 0; i < temp.length; i++) { arr[i] = Integer.valueOf(temp[i]); } System.out.println(cal(arr)); sc.close(); } public static int cal(int[] arr) { // TODO Auto-generated method stub Set<Integer> set = new HashSet<Integer>(); for (int i = 0; i < arr.length; i++) { for (int j = i + 1; j < arr.length; j++) { if (arr[i] + arr[j] == 0) { set.add(i); set.add(j); } } } return set.size() / 2; } // 1,-1,-1,1,2,-2,3 }