美团笔试 0326 编程题 Java(更新中)
第一题:字符串重排
题目描述:
给你一个只包含小写字符的字符串s,你可以按任意顺序重排这个字符串中的字符,请问重排过后的字符串中,最多能有多少个'acbcca'子串?
例如,字符串'dacbccab' 中含1个'acbcca' 子串,按其他方式重排后最多也只能包含1个' acbcca' 子串;字符串acbccaacccb'中含1个'acbcca' 子串,但重排成'acbcacbcca' 后包含了2个'acbcca' 子串。
样例输入1:
dacbccab
样例输出:
1
样例输入2:
acbccbbcccb
样例输出:
2
import java.util.*;
public class Main{
public static void main(String []args){
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
System.out.print(resetString(s));
}
public static int resetString(String s){
Map<Character,Integer> hash=new HashMap<Character,Integer>();
for(int i=0;i<s.length();i++){
char c=s.charAt(i);
if(c=='a' || c=='b' || c=='c'){
//关于getOrDefault()方法
//当Map集合中存在这个key时,就使用这个key的value,(若是数值型可以在此基础上进行运算),如果没有就使用默认值defaultValue。
hash.put(s.charAt(i),hash.getOrDefault(c,0)+1);
}
}
int countA=hash.get('a');
int countB=hash.get('b');
int countC=hash.get('c');
//找到出现最少次数的字母,看能完整构成几次
//原字符串包含三个a,进行重排,a首尾相接,"acbccacbcca",三个a也能出现两次
int ans=Math.min(Math.min(countA-1,countB),countC/3);
return ans;
}
}第二题:数轴两点汇合距离差最小
题目描述:
给定一个递增数组,要求找到一个点,使这个点到1和n的距离之差最小。(大概题意)
样例输入1:
2
5 7
样例输出:
2
package com.leetcodeDp.knapsack;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] num = new int[n];
for (int i = 0; i < n; i++) {
num[i] = sc.nextInt();
}
if (n == 2){
//Math.abs(x)函数返回指定数字 "X" 的绝对值
System.out.println(Math.abs(num[0] - num[1]));
}else {
int res = Math.abs(num[0] - num[n - 1]);
for (int i = 1; i < n - 1; i++) {
res = Math.min(res, Math.abs(num[i] - num[0] - num[n - 1] + num[i]));
} System.out.println(res);
}
}
}#美团笔试##美团##笔试题目#
海康威视公司氛围 1020人发布
查看7道真题和解析