代码如下:
import org.junit.Test;
public class ReduplicatedWords {
/*
* 化简叠词:如aaabccd,化简为a3bc2d
*/
@Test
public void reduplicatedWords() {
String s = "aaabbbbccdddfgsss";
String res = "";
int count = 1;
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) == s.charAt(i - 1)) {
count++;
// 如果是最后类字符,需特殊处理
if (i == s.length() - 1) {
res = res + s.charAt(i) + count;
}
continue;
} else {
res = res + s.charAt(i - 1) + count;
count = 1;
}
}
System.out.println(res);
}
}