在比赛中有人问我这个问题。给定仅包含M和L的字符串,我们可以将任何“ M”更改为“ L”或将任何“ L”更改为“ M”。该函数的目的是计算为了达到所需的最长M间隔长度K
而必须进行的最少更改。例如,给定S =“ MLMMLLM”并且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;
}
Helenr
倚天杖
相关分类