问题描述

思路1
- 统计每一种字符的个数。
- 计算所有数字的总和与平均值。
- 统计需要改变的长度
- 统计超出平均值的字符, 将其替换为X
- 找到字符串中k个X的最短字串长度
代码解析
public class Main {
public static int solution(String input) {
// Please write your code here
int numA = 0, numS = 0, numD = 0, numF = 0
for (int i = 0
char c = input.charAt(i)
if (c == 'A')
numA++
if (c == 'S')
numS++
if (c == 'D')
numD++
if (c == 'F')
numF++
}
int replace = 0
boolean replaceA = false, replaceS = false, replaceD = false, replaceF = false
if (numA > input.length() / 4) {
replaceA = true
input=input.replace('A', 'X')
}
else
replace += input.length() / 4 - numA
if (numS > input.length() / 4) {
replaceS = true
input=input.replace('S', 'X')
}
else
replace += input.length() / 4 - numS
if (numD > input.length() / 4) {
replaceD = true
input=input.replace('D', 'X')
}
else
replace += input.length() / 4 - numD
if (numF > input.length() / 4) {
replaceF = true
input=input.replace('F', 'X')
}
else
replace += input.length() / 4 - numF
int min = input.length()
int tmp = 0
for (int i = 0
if (input.charAt(i) != 'X')
continue
int len = 0
for (int j = i
if (input.charAt(j) == 'X') {
len++
}
tmp++
if (len == replace)
break
}
if (tmp < min)
min = tmp
tmp=0
}
return min
}
public static void main(String[] args) {
// You can add more test cases here
System.out.println(solution("ADDF") == 1)
System.out.println(solution("ASAFASAFADDD") == 3)
}
}