杭州电子科技大学ACM1020 JAVA

一、题目

Problem Description
Given a string containing only ‘A’ - ‘Z’, we could encode it using the following method:

  1. Each sub-string containing k same characters should be encoded to “kX” where “X” is the only character in this sub-string.
  2. If the length of the sub-string is 1, ‘1’ should be ignored.

Input
The first line contains an integer N (1 <= N <= 100) which indicates the number of test cases. The next N lines contain N strings. Each string consists of only ‘A’ - ‘Z’ and the length is less than 10000.

Output
For each test case, output the encoded string in a line.

Sample Input
2
ABC
ABBCCC

Sample Output
ABC
A2B3C

二、中文解释

根据第一行输入的数字,循环输入字符串(仅包含A-Z),如把相邻的相同字符串如AAA表示成3A。
input ABBCCCBB
output A2B3C2B

三、代码

import java.util.Scanner;

public class ACM1020_2 {
    public static void main(String[] args) {
        int line;
        Scanner sc = new Scanner(System.in);
        line = sc.nextInt();
        while(line-- >0){
            String str = "";
            str = sc.next();
            char c = str.charAt(0);//初始化一个不属于字母的字符
            int time = 0;
            for(int i = 0; i < str.length();i++){
            if (str.charAt(i)==c){
                time++;
            }else{
                if(time>1)
                System.out.print(time);
                System.out.print(c);
                time = 1;
            }
                c = str.charAt(i);
            }
            if(time>1)
            System.out.print(time);
            System.out.print(c);
            //if(line != 0) 哎,有的题目要加,有的题目不用加
            System.out.println("");
        }
    }
}

四、遇到的问题

一、英语水平不够,一开始题目理解出了问题
二、最后的格式控制,输出一行的字符串之后就要换行,我还考虑了最后一次不用换行,结果Presentation Errorm.需要注意的是这一题不需要考虑这个情况

人最宝贵的是生命,每个人的生命只有一次,所以你应该在这样度过你的一生:当你回首往事的时候,既不因虚度年华而悔恨,也不因碌碌无为而羞愧。

猜你喜欢

转载自blog.csdn.net/weixin_40940027/article/details/81431466