问题 A: 统计字符串
题目描述
给定一个字符串str,返回str的统计字符串。例如“aaabbbbcccd”的统计字符串为“a_3_b_4_c_3_d_1”。
输入
输入一行字符串(1<=长度<=10^5)。
输出
输出一行字符串,代表统计字符串。
offerofferzainaliiiiii
hhhaaa
不知道为什么用Java就对了,C++用结构体却不行,我表示对学校的OJ十分无奈
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static class Chat{
public char c;
public int num;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Chat> list=new ArrayList<>();
String T;
while (sc.hasNext()) {
int cnt=0;
T = sc.next();
list.clear();
int flag=0;
for(int i=0;i<T.length();i++){
if(i==0){
Chat chat=new Chat();
chat.c=T.charAt(i);
chat.num=1;
list.add(chat);
flag++;
}else {
char temp = T.charAt(i);
if (temp != T.charAt(i - 1)) {
Chat chat = new Chat();
chat.c = temp;
chat.num = 1;
list.add(chat);
flag++;
} else {
list.get(flag-1).num++;
}
}
}
for(Chat c:list){
if(flag==1){
System.out.println(c.c+"_"+c.num);
}else
System.out.print(c.c+"_"+c.num+"_");
flag--;
}
}
}
}