输入一行字符串,代表str。
输出一行字符串,代表统计字符串。
offerofferzainaliiiiii
o_1_f_2_e_1_r_1_o_1_f_2_e_1_r_1_z_1_a_1_i_1_n_1_a_1_l_1_i_6
hhhaaa
h_3_a_3
时间复杂度,空间复杂度
。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static String getCountString(String str) {
if (str == null || str.equals("")) {
return null;
}
// 初始时字符串res只包含str的第0个字符,同时num = 1
StringBuilder res = new StringBuilder();
res.append(str.charAt(0));
int num = 1;
for (int i = 1; i < str.length(); i++) {
// 当前重复的字符已经结束
if (str.charAt(i) != str.charAt(i - 1)) {
res.append('_').append(num).append('_').append(str.charAt(i));
num = 1;
} else {
num++;
}
}
// 当遍历结束时,最后一种字符的次数还没有放入res,需要加上,
return res.append('_').append(num).toString();
}
// private static String concat(String s1, String s2, String s3) {
// // res(s1) + "_num(s2)" + "动态判断是否需要_的s3(下一个字符)"
// return s1 + "_" + s2 + (s3.equals("") ? s3 : "_" + s3);
// }
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String line= null;
while ((line = bf.readLine())!=null){
System.out.println(getCountString(line));
}
}
}