首页 > 试题广场 >

字符串的统计字符串

[编程题]字符串的统计字符串
  • 热度指数:2430 时间限制:C/C++ 2秒,其他语言4秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一个字符串str,返回str的统计字符串。例如“aaabbbbcccd”的统计字符串为“a_3_b_4_c_3_d_1”。

输入描述:
输入一行字符串,代表str


输出描述:
输出一行字符串,代表统计字符串。
示例1

输入

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
示例2

输入

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));
        }
    }

}

发表于 2020-04-06 15:46:05 回复(0)

问题信息

上传者:小小
难度:
1条回答 5440浏览

热门推荐

通过挑战的用户

查看代码