题目
试题 算法提高 字符串压缩
资源限制
时间限制:1.0s 内存限制:256.0MB
问题描述
编写一个程序,输入一个字符串,然后采用如下的规则对该字符串当中的每一个字符进行压缩:
(1) 如果该字符是空格,则保留该字符;
(2) 如果该字符是第一次出现或第三次出现或第六次出现,则保留该字符;
(3) 否则,删除该字符。
例如,若用户输入“occurrence”,经过压缩后,字符c的第二次出现被删除,第一和第三次出现仍保留;字符r和e的第二次出现均被删 除,因此最后的结果为:“ocurenc”。
输入格式:输入只有一行,即原始字符串。
输出格式:输出只有一行,即经过压缩以后的字符串。
输入输出样例
样例输入
occurrence
样例输出
ocurenc
package 蓝桥练习;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
//下标值
int index = 0;
Scanner s = new Scanner(System.in);
String s1 = s.nextLine();
//压缩前的字符
char oldChar[] = s1.toCharArray();
//存储字符的相关信息
Count[] counts = new Count[oldChar.length];
for(int i=0;i<oldChar.length;i++) {
counts[i] = new Count();
for(int j =0; j<i;j++) {
//比较这个字符此时出现的次数
if(oldChar[i] == oldChar[j]) {
counts[i].num ++;
}
}
//存储相应的字符信息
counts[i].c = oldChar[i];
}
/**
* 测试存储的信息
for(int i =0;i<counts.length;i++) {
System.out.println(counts[i].c+" "+counts[i].num);
}
*/
//压缩后的字符
char newChar[] = new char[oldChar.length];
//存储压缩字符串的信息
for(int i = 0;i<counts.length;i++) {
if(counts[i].c == ' ') {
//若字符为空格
newChar[index++] = counts[i].c;
}else {
if(counts[i].num == 1 ||counts[i].num == 3 || counts[i].num == 6) {
//如果出现的次数为1,3,6则保存
newChar[index++] = counts[i].c;
}
}
}
//存储结果值
String result = "";
for(int i =0;i<index;i++) {
result = result+newChar[i];
}
System.out.println(result);
s.close();
}
}
//用于存储字符的次数与字母
class Count{
char c;
int num;
Count(){
//一开始就有自己的一次字符
num = 1;
}
}