洛谷P3741 honoka的键盘Java题解

这题的思路有俩:

思路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;
public class P3741honoka的键盘 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        String s = sc.next();
        String t = "VK";
        int count = 0;
        //原来字符串的长度.。原来的字符串长度减去替换后的得到VK一共的长度,在/2便是换了几个VK
        int start = s.length();
        String end = s.replace("VK","");
        char[] c = end.toCharArray();
        //l是将字符串中VK字符替换后剩余字符串的长度
        int l = s.replace("VK", "").length();
        boolean isVK = false;
        //替换了几次
        count = (start - l) / 2;
        //判断替换过后的剩余字符串中是否出现可以替换的
        for (int i = 0; i < end.length()-1; i++) {
            if (c[i] ==  c[i + 1]  ) {
                isVK = true;
                break;
            }
        }
        if (isVK) {
            System.out.println(count + 1);
        } else {
            System.out.println(count);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/Chen__sir__/article/details/122660906