【题目】
给定一个字符串str,返回str的统计字符串
例如,"aaabbadddffc"的统计字符串为"a_3_b_2_a_1_d_3_f_2_c_1"
1 public String count(String str) 2 { 3 if(str == null || str.equals("")) 4 { 5 return ""; 6 } 7 8 char[] chas = str.toCharArray(); 9 String cstr = String.valueOf(chas[0]);10 int num = 1;11 for(int i = 1; i < chas.length; i++)12 {13 if(chas[i] != chas[i - 1])14 {15 cstr = concat(cstr, String.valueOf(num), String.valueOf(chas[i]));16 num = 1;17 }18 else19 {20 num++;21 }22 }23 24 return concat(cstr, String.valueOf(num), "");25 }26 27 28 public String concat(String s1, String s2, String s3)29 {30 return s1 + "_" + s2 + (s3.equals("") ? s3 : "_" + s3);31 }
【题目】
给定一个字符串的统计字符串cstr,再给定一个整数index,返回cstr所代表的原始字符串上的第index个字符
例如,"a_1_b_100"所代表的原始字符串上第0个字符是'a',第50个字符是'b'
1 public char getCharAt(String str, int index) 2 { 3 if(str == null || str.equals("") || index < 0) 4 { 5 return 0; 6 } 7 8 char[] chas = str.toCharArray(); 9 boolean stage = true;10 char cur = 0;11 int sum = 0;12 int num = 0;13 for(int i = 0; i < chas.length; i++)14 {15 if(chas[i] == '_')16 {17 stage = !stage;18 }19 else if(stage)20 {21 sum += num;22 if(sum > index)23 {24 return cur;25 }26 num = 0;27 cur = chas[i];28 }29 else30 {31 num = num * 10 + chas[i] - '0';32 }33 }34 return sum + num > index ? cur : 0;35 }36 37
来源:左程云老师《程序员代码面试指南》