题源:https://cn.vjudge.net/problem/757489/origin
Description
Tonio has a keyboard with only two letters, “V” and “K”.
One day, he has typed out a string s with only these two letters. He really likes it when the string “VK” appears, so he wishes to change at most one letter in the string (or do no changes) to maximize the number of occurrences of that string. Compute the maximum number of times “VK” can appear as a substring (i. e. a letter “K” right after a letter “V”) in the resulting string.
Input
The first line will contain a string s consisting only of uppercase English letters “V” and “K” with length not less than 1 and not greater than 100.
Output
Output a single integer, the maximum number of times “VK” can appear as a substring of the given string after changing at most one character.
Examples
Input
VK
Output
1
Input
VV
Output
1
Input
V
Output
0
Input
VKKKKKKKKKVVVVVVVVVK
Output
3
Input
KVKV
Output
1
——————————————————————————————————
分析:小明有个键盘,但只有V、K两个键。输入一串V和K组成的字符串儿,然后你可以将其中一个K变成V或者V变成K,使得"VK"出现的次数达到最大,输出这个最大的次数。
这个需要多种情况考虑,下面的代码是一种比较复杂的方法。因为遇到已有的VK没有置为别的字符,所以判断能否出现增加的那个VK时比较麻烦,
下面外接一个方便一点的代码:https://blog.csdn.net/daoshen1314/article/details/86661029
下面是我的AC代码:
#include<stdio.h>
#include<string.h>
int main(){ // 注意多分析几种情况!!!
int i,count=0,flag=0;
char s[101];
gets(s);
if(strlen(s)==1){ //若只有一个字符,输出0结束。
printf("0");
return 0;
}
if(strlen(s)==2){ //若有两个字符,除了这两个字符是KV,否则都可以变成一个VK
if(!(s[0]=='K'&&s[1]=='V')){
printf("1");return 0;
}
}
else{ //若有三个及以上的字符
for(i=0;i<(strlen(s)-1);i++){ //遍历一遍字符串 看见VK就++
if(s[i]=='V')
if(s[i+1]=='K')
count++;
}
for(i=0;i<(strlen(s)-2);i++){ //遍历一遍字符串 如果在中间(除去第一个和最后一个)
if(s[i]==s[i+1]&&s[i]==s[i+2]) //有连续三个相同,那么说明可以增加一个VK
flag=1;
}
if(s[0]=='K'&&s[1]=='K') //这里检查头和尾,若有头有两个K或尾有两个V 就说明可以++
flag=1;
if(s[strlen(s)-1]=='V'&&s[strlen(s)-2]=='V')
flag=1;
}
if(!flag) printf("%d",count);
else printf("%d",count+1);
return 0;
}