【发布时间】:2018-10-10 21:03:41
【问题描述】:
我在一次比赛中被问到这个问题。
给定一个仅包含 M 和 L 的字符串,我们可以将任何“M”更改为“L”或将任何“L”更改为“M”。此函数的目标是计算为达到所需的最长 M 间隔长度 K,我们必须进行的最少更改次数。
例如,给定 S = "MLMMMLM" 和 K = 3,函数应该返回 1。我们可以改变位置 4 的字母(从 0 开始计数)得到 "MLMMMLM",其中字母 "M" 的最长间隔是正好三个字符长。
再举个例子,给定 S = "MLMMMLMMMM" 和 K = 2,函数应该返回 2。例如,我们可以修改位置 2 和 7 的字母,得到字符串 "MLLMMLMLMM",它满足期望属性。
这是我到目前为止所尝试的,但我没有得到正确的输出: 我正在遍历字符串,只要最长的字符数超过 K,我就用 L 替换 M。
public static int solution(String S, int K) {
StringBuilder Str = new StringBuilder(S);
int longest=0;int minCount=0;
for(int i=0;i<Str.length();i++){
char curr=S.charAt(i);
if(curr=='M'){
longest=longest+1;
if(longest>K){
Str.setCharAt(i, 'L');
minCount=minCount+1;
}
}
if(curr=='L')
longest=0;
}
if(longest < K){
longest=0;int indexoflongest=0;minCount=0;
for(int i=0;i<Str.length();i++){
char curr=S.charAt(i);
if(curr=='M'){
longest=longest+1;
indexoflongest=i;
}
if(curr=='L')
longest=0;
}
Str.setCharAt(indexoflongest, 'M');
minCount=minCount+1;
}
return minCount;
}
【问题讨论】:
-
你是如何处理其他案件的?不能有需要用M替换L的情况吗?代码在哪里?
-
我已编辑代码以包含该条件。但它不是最佳的。
-
最优是什么意思?期望的运行时复杂度是多少?是不是给出了错误的答案?
-
显然应该有人在 ML 中添加解决方案 :)
-
@GaganDeep:你想在这次编程比赛中作弊吗? app.codility.com/programmers/custom_challenge/… - 减少复杂性 - Codility 和 ASML?
标签: java c# algorithm data-structures dynamic-programming