美團筆試測試方向第二場算法題
第一題:字符串匹配
有相對應(yīng)的匹配模式
public static void main(String[] args) { int m ; Scanner in = new Scanner(System.in); m = in.nextInt(); in.nextLine(); for(int i = 0; i < m ;i++){ System.out.println(check(in.nextLine())); } } public static String check(String transportId){ if(transportId.length() < 2) return "Invalid"; String str = transportId.substring(0,2); String context = transportId.substring(2); switch (str){ case "SF" : if(context.length() != 10) return "Invalid"; for(char c : context.toCharArray()){ if (c < '0' || c > '9'){ return "Invalid"; } } return "Normal"; case "EX" : if(context.length() != 10) return "Invalid"; for(int i = 0; i< context.length(); i++){ if(i < 2){ if(context.charAt(i) < 'A' || context.charAt(i) > 'Z'){ return "Invalid"; } } if(context.charAt(i) < '0' || context.charAt(i) > '9'){ return "Invalid"; } } return "Express"; case "IN": if(context.length() != 9) return "Invalid"; int sum = 0; for(int i = 0; i< context.length(); i++){ if(i < 3){ if(context.charAt(i) < 'A' || context.charAt(i) > 'Z'){ return "Invalid"; } } if(context.charAt(i) < '0' || context.charAt(i) > '9'){ return "Invalid"; } if(i >= context.length()-3){ sum += context.charAt(i) - '0'; } } if(sum % 2 == 0) return "InterNational"; else return "Invalid"; default: if(transportId.length() != 12) return "Invalid"; if(transportId.charAt(0) == '0') return "Invalid"; for(char c : transportId.toCharArray()){ if(c > '9' || c < '0') return "Invalid"; } return "E-commerce"; } }
通過62.5% 后面的特殊情形想不到了
第二題
字符匹配
遇到R反轉(zhuǎn) 遇到Z回退操作(如果是R就反轉(zhuǎn)回來,如果是添加操作就刪除)
static StringBuilder res; static String target; public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); in.nextLine(); for (int i = 0;i < n;i++){ target = in.nextLine(); res = new StringBuilder(); dfs(0,false,0); System.out.println(res.toString()); } } public static void dfs(int i,boolean isRev, int addWhat){ if(i >= target.length()) return; //嘗試回溯 if(target.charAt(i) == 'Z'){ if(isRev){ res.reverse(); isRev = false; } if(addWhat != 0){ res.deleteCharAt(addWhat); addWhat = 0; } } if(target.charAt(i) == 'R') { res.reverse(); isRev = true; }else{ isRev = false; } //添加參數(shù) addWhat = 0; if(target.charAt(i) != 'R' && target.charAt(i) != 'Z') { res.append(target.charAt(i)); addWhat = res.length() - 1; } //傳遞的參數(shù)為i+1 這一步的操作 dfs(i+1,isRev,addWhat); }
通過50%,應(yīng)該還需要回溯,想不到了
第三題
求和 給定l1 r1 l2 r2
存在以下關(guān)系 f(a,b) 當(dāng)a是b的倍數(shù)時 f(a,b) = 1反之為0
現(xiàn)在要求和
貼一段暴力代碼
for(int j = l2 ;j<=r2;j++){ for(int i = l1;i<=r1;i++){ sum+= f(i,j); } }
麻了