这题的思路有俩:
思路1:将字符串转化成字符串数组,如何比对每相邻的值是否与VK相等,然后赋其他值,防止二次判断,这样先将VK找出,随后进行替换,如果出现VV或KK则替换一个即可变成VK,KV则不行
思路2:利用String中的replace方法先找替换VK成“”,再用原来字符串长度减去替换后的字符串长度除2可得换掉的VK,然后将替换VK后的字符串转换成字符串字符,判断里面是否出现VV、KK,如果有,总数+1即可。PS这个思路只拿了96分。
思路1代码
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner cin = new Scanner (System.in);
int n = cin.nextInt();
String s = cin.next();
char[] ch = s.toCharArray();
int num = 0;
boolean isVk = false;
for(int i = 0; i < s.length()-1; i++) {
if(ch[i] == 'V' && ch[i+1] == 'K') {
num++;
ch[i] = 'X';ch[i+1] = 'Y';
}
}
for(int i = 0; i < s.length()-1; i++) {
if(ch [i] == ch [i+1])
isVk = true;
}
if(isVk)
System.out.println(num+1);
else
System.out.println(num);
}
}
思路2代码:
import java.util.Scanner;
pu