4.1 携程Java笔经
4.1日携程笔试,第一题SQL答案
public static void main(String[] args) { // 测试用例 // String[] str = {"select t.id, t.name, t.tag_id\n" + // "from (\n" + // " select user.id, user.name, tag.tag_id\n" + // " from user\n" + // " inner join user_tag\n" + // ") t"}; //// System.out.println(Arrays.toString(str)); // for (int i = 0; i < str.length; i++) { // System.out.println(i+": "+str[i]); // } String[] str = new String[50]; String[] strings = multiInput(str); findTable(strings); } /** * 从完整的SQL语句中找到表名 * * @param str */ public static void findTable(String[] str) { // 1. 首先将字符串数组切割(按照from) String[] s = Arrays.toString(str).split("from"); String[] s2 = Arrays.toString(str).split("inner join"); String print = null; // 2. 判断from和inner join后面是( 还是表名 for (int i = 1; i < s.length; i++) { // 打印所有的子串 // System.out.println(i + ": " + s[i]); // 截取每一个子字符串 String sub= s[i].substring(0, s[i].length() - 1); // 去除首尾空格 String s1 = sub.trim(); // System.out.println("起点" + s1 + "终点"); // 按照空格截断每一个子串(先去除首尾的空格) String[] ss = s1.split(" "); // System.out.println(Arrays.toString(ss)); // System.out.println(ss[0]); if (ss[0] != "("){ // System.out.print(ss[0]); print = ss[0]+"\n"; } } // 下面是inner join的部分 for (int i = 1; i < s2.length; i++) { String sub2 = s2[i].substring(0,s2[i].length() - 1); String s11 = sub2.trim(); String[] ss2 = s11.split(" "); // System.out.print(ss2[0]); print += ss2[0]; } // 注意:这里记得清除带数组格式的"," String s3 = print.replaceAll(",", ""); System.out.println(s3); } public static String[] multiInput(String[] str){ Scanner in = new Scanner(System.in); String[] strArr = str; int count = 0; for (int i = 0; i < 50; i++) { strArr[i] = in.nextLine(); // 判断是否为两个换行 if (strArr[i].replaceAll(" ", "").length() == 0) { // System.out.println(strArr[i]); count = i; break; } } // 4. 将数据整理成一组新的有效数组 String[] strNew = new String[count]; for (int i = 0; i < count; i++) { strNew[i] = strArr[i]+"\n"; } // System.out.println(Arrays.toString(strNew)); // 5. 转为字符串 // StringBuffer stringBuffer = new StringBuffer(strNew.length); // for (int i = 0; i < strNew.length; i++) { // stringBuffer.append(strNew[i]); // } // System.out.println(stringBuffer.toString()); return strNew; }大家有兴趣可以跑下,另外吐槽下携程的两道hard真的难!