1.通过键盘输入一串小写字母(a-z)组成的字符串,请编写一个字符串压缩程序,将字符串中连续出现的重复字母进行压缩,并输出压缩后的字符串。 压缩规则如:
1、仅压缩连续重复出现的字符数。 如:字符串” abcbc” 由于无连续重复字符, 不压缩 2、压缩后格式为“字符重复的次数+字符”。 如:字符串”
xxxyyyyyyz” 压缩后” 3x6yz”
代码:
String str1 = "";
char front = str.charAt(0);
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == front) {
count++;
} else {
str1 += count;
str1+=front;
front = str.charAt(i);
count = 1;
}
}
str1+=count;
str1+=front;
System.out.println(str1);
网友评论