1,一道练习题
String string=“aabaaaaaaabccbbccccccccb”;
查询 字符串中每种字符出现的最大间隔
比如第一个a和第二个a之间是0 第二个a和第三个a之间 是1
我的答案是
public class AtomicIntegerTest {
public static void main(String[] args) {
String string="aabaaaaaaabccbbccccccccb";
List<String> relist=new ArrayList<>();
Set<String> set=new HashSet<>();
int count=0;
char[] ch=string.toCharArray();
for (int i = 0; i < ch.length; i++) {
set.add(ch[i] + "");
}
HashMap<String,Object> map=new HashMap<>();
set.forEach(x->{
String in= x;
char c=in.charAt(0);
List<Integer> list=new ArrayList<>();
for (int i = 0; i < ch.length; i++) {
System.out.print(ch[i]+",");
System.out.println("传来的值"+c+",");
if (c==ch[i]) {
list.add(i+1);
}
}
map.put(x,list);
//分组 查询有多少元素
System.out.println(list);
int i = maxGap(list.stream().toArray(Integer[]::new));
System.out.println("最大差"+i);
int i1 = i - 1;
relist.add(x+"的最大差是"+i1);
});
System.out.println(relist);
}
public static int maxGap(Integer ...arr) {
if (arr == null || arr.length < 2)
return 0;
int len = arr.length;
//表示桶内是否含有元素
boolean[] hasNum = new boolean[len + 1];
//表示桶内元素中的最小值
int[] mins = new int[len + 1];
//表示桶内元素中的最大值
int[] maxs = new int[len + 1];
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
int bid = 0;
//找到数组中的最大值和最小值
for (int e : arr) {
min = Math.min(min, e);
max = Math.max(max, e);
}
if (min == max)
return 0;
for (int i = 0; i < len; i++) {
bid = bucketId(arr[i], len, min, max);
mins[bid] = hasNum[bid] ? Math.min(mins[bid], arr[i]) : arr[i];
maxs[bid] = hasNum[bid] ? Math.max(maxs[bid], arr[i]) : arr[i];
hasNum[bid] = true;
}
int res = 0;
int preMax = maxs[0];
for (int i = 1; i <= len; i++) {
if (hasNum[i]) {
res = Math.max(res, mins[i] - preMax);
preMax = maxs[i];
}
}
return res;
}
//判断整数item所属桶的id
public static int bucketId(int num, int len, int min, int max) {
return ((num - min) * len / (max - min));
}
}