题目:
给定一个字符串str,返回str的统计字符串。例如:‘’aaabbadddffc‘’的统计字符串为‘’a_3_b_2_a_1_d_3_f_2_c_1‘’。
解答:
1.如果str为空,那么统计字符串不存在。
2.如果str不为空。首先生成String类型的变量res,表示统计字符串,还有整型变量num,代表当前字符的数量。初始时字符串只包含第0个字符(str[0]),同时num=1。
3.从str[1]位置开始,从左到右遍历str,假设遍历到i位置。如果str[i]==str[i-1]说明当前连续出现的字符串还没有结束,令num++,然后继续遍历下一个字符。
如果str[i]!=str[i-1]说明当前连续出现的字符str[i-1]已经结束,令res=res+“_”+num+"str[i]"。然后令num=1,继续遍历。
4.最后令res=res+"_"+num。
public class CountString {
public static String getCountString(String str){
if(str == null || str.equals("")){
return "";
}
char[] chas = str.toCharArray();
String res = String.valueOf(chas[0]);
int num = 1;
for(int i = 1; i < chas.length; i++){
if(chas[i] != chas[i-1]){
res = concat(res, String .valueOf(num), String.valueOf(chas[i]));
num = 1;
}else{
num++;
}
}
return concat(res, String.valueOf(num), "");
}
public static String concat(String s1, String s2, String s3){
return s1 + "_" + s2 + (s3.equals("") ? s3 : "_" + s3);
}
public static void main(String[] args) {
String str = "aaabbaffdddc";
System.out.println(getCountString(str));
}
}
参考资料:《程序员面试代码指南》左程云 著