编码 (java实现)

Problem Description

给你一个由大写字母组成的组成的字符串,你可以用如下规则对其进行编码:
1、 包含K个相同字母的连续字符串可以用KX表示,其中X是相同的字母。
2、 如果K为1,不输出K

Input

 输入有多组,直到文件结束。每组一个字符串,长度为10000以内

Output

 输出编码后的字符串。

Sample Input

ABC
ABBCCC

Sample Output

ABC
A2B3C

Hint

 

Source

lin
 
 1 import java.util.*;
 2 
 3 public class Main {
 4     public static void main(String[] args) {
 5         Scanner sc = new Scanner(System.in);
 6         while (sc.hasNext()){
 7             String str = sc.next();
 8             int count = 1;  // 创建计数变量,记录字母出现次数
 9             char key = 0;   
10             for (int i = 1; i < str.length()+1; i++) {  // 因为要照顾到最后一个元素的情况,所以用str.length+1
11                 if(i < str.length()){  // 若最后一个字母与前面的相同
12                     key = str.charAt(i-1);  // 固定前一个变量
13                     char ch = str.charAt(i);  // 创建游动变量,遍历字符串
14                     if(ch == key) { 
15                         count++;  // 字幕出现次数加一
16                         continue;  // 继续判断后面的字母
17                     }
18                 }
19                 else{  // 若最后一个字母与前面的不同
20                     key = str.charAt(str.length()-1);  // 判定最后一个
21                 }
22                 if(count == 1){
23                     System.out.printf("%c", key);
24                 }
25                 else{
26                     System.out.printf("%d%c", count, key);
27                     count = 1;
28                 }
29             }
30             System.out.println();
31         }
32     }
33 }
原文地址:https://www.cnblogs.com/sugerandmaster/p/11502572.html