笔试 2020.10.20

it2023-10-19  67

阿里巴巴笔试

1

给定一个最K 求String的长度大于K的subString中 出现次数最多的一个

import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int minLen = sc.nextInt(); String useless = sc.nextLine(); String str = sc.nextLine(); System.out.println(getF(str,minLen) ); } public static String getF(String str, int minLen) { char[] chars = str.toCharArray(); Map<String,Integer> hashmap = new HashMap<>(); for(int i=0;i<chars.length;i++){ if(i+minLen >=chars.length) break; // System.out.println(i+minLen); String sub = String.valueOf(chars,i,minLen); hashmap.put(sub,hashmap.getOrDefault(sub,0)+1); } int max =0; String res =""; for(String v:hashmap.keySet()){ if(hashmap.get(v) > max) { max = hashmap.get(v); res = v; } } return res; } }

2

求一个数组 长度大于二的子序列 并且满足a[i] & a[j] == a[i] 的子序列个数

import java.util.*; public class Main { private static int count=0; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int len = sc.nextInt(); int[] nums = new int[len]; for(int i=0;i<len;i++){ nums[i] = sc.nextInt(); } List<Integer> temp = new ArrayList<>(); backtrack(nums,len,temp,0); System.out.println(count%1000000007); } public static void backtrack(int[] nums, int len, List<Integer> temp,int index) { for(int i=index;i<len;i++){ temp.add(nums[i]); backtrack(nums,len,temp,i+1); temp.remove(temp.size()-1); } if(temp.size() >=2) { for(int i=0;i<temp.size()-1;i++){ for(int j=i+1;j<temp.size();j++){ if((temp.get(i) & temp.get(j)) != temp.get(i)) return; } } count++; } } }
最新回复(0)