官方数据错误,不完整的循环节也输出了答案,例如 abcde 当 k 取 3 的时候,可以修改为 abc,这是不符合题意的。
如果非要过官方数据,修改代码 -1 输出的条件为 length < k,且将字符串长度截断为abc
以下解题先不考虑错误数据
解题思路:
1、首先判断能否将字符串整分,即判断s.length() 能否整除k,可以的话,再继续往下走,否则返回答案-1
2、既然可以整分,那就手动分开吧,创建一个二维数组,该数组每行k个元素,共s.length()/k行,其实也可以不使用二维数组,直接对字符串进行操作,但使用二维数组更直观一些。
3、统计每列中各字符出现的个数,然后把字符都修改成出现频率最高的那个字符,并统计修改次数(这里我是用HashMap来统计的)
例如:2 aabbaa
| a | a |
| b | b |
| a | a |
第二列中,a出现的次数最多,需要把所有字符都改为a,需要改动一次
共改动2次,输出2即可
参考代码:
注意:这个代码通不过官方的检测,但实际是对的,因为官方数据有错误!下边也会给出能通过官方检测的代码
import java.util.*;
public class Main {
public static int result;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int k = scan.nextInt();
String s = scan.next();
if (s.length() % k != 0) {
result = -1;
} else {
int len = s.length() / k;
char[][] target = new char[k][len];
for (int i = 0; i < k; i++) {
for (int j = 0; j < len; j++) {
target[i][j] = s.charAt(i * len + j);
}
}
for (int i = 0; i < len; i++) {
//统计每列中字符出现的次数
Map<Character, Integer> statistics = new HashMap<Character, Integer>();
for (int j = 0; j < k; j++) {
char ch = target[j][i];
if (statistics.containsKey(ch)) {
int count = statistics.get(ch);
count = count + 1;
statistics.put(ch, count);
} else {
statistics.put(ch, 1);
}
}
//计算将将该列中的字符都改为该列出现次数最多的字符需要改动几次,并添加到result中
int max = 0;
for (Character ch : statistics.keySet()) {
int temp = statistics.get(ch);
if (temp > max) {
max = temp;
}
}
result += k - max;
}
}
System.out.print(result);
scan.close();
}
}修改后的代码:
import java.util.*;
public class Main {
public static int result;
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int k=scan.nextInt();
String s=scan.next();
if(s.length()<k){
result=-1;
}else{
int length=s.length()-s.length()%k;
int len=length/k;
char[][] target=new char[k][len];
for (int i = 0; i < k; i++) {
for (int j = 0; j < len; j++) {
target[i][j]=s.charAt(i*len+j);
}
}
for (int i = 0; i < len; i++) {
//统计每列中字符出现的次数
Map<Character,Integer> statistics= new HashMap<Character, Integer>();
for (int j = 0; j < k; j++) {
char ch=target[j][i];
if(statistics.containsKey(ch)){
int count=statistics.get(ch);
count=count+1;
statistics.put(ch,count);
}else{
statistics.put(ch,1);
}
}
//计算将将该列中的字符都改为该列出现次数最多的字符需要改动几次,并添加到result中
int max=0;
for (Character ch: statistics.keySet() ) {
int temp=statistics.get(ch);
if(temp>max){
max=temp;
}
}
result+=k-max;
}
}
System.out.print(result);
scan.close();
}
}0.0分
3 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复