Java编写方法实现字符串压缩的功能,连续的 n 个字符 x 表示为 xn,例如 aaaa 表示为a4,
如果只出现一次直接输出即可。例如输入aaaaaaaabbbccdddeeebbba,输出a7b3c2d3e3b3a...
如果只出现一次直接输出即可。例如输入 aaaaaaaabbbccdddeeebbba,输出a7b3c2d3e3b3a
展开
1个回答
展开全部
package demo1;
public class Demo2 {
public static String reduceString(final String str) {
StringBuffer result = new StringBuffer();
final int count = str.length();
char c1 = str.charAt(0);
int sum = 1;
for (int i = 1; i < count; i++) {
char c2 = str.charAt(i);
if (c1 == c2)
{
sum++;
continue;
}
result.append(c1).append(sum);
c1 = c2;
sum = 1;
}
result.append(sum).append(c1);
return result.toString();
}
public static void main(String[] args) {
System.out.println(reduceString("aaaaaaaabbbccdddeeebbba"));
}
}
追问
要求从键盘输入
追答
package demo1;
import java.util.Scanner;
public class Demo2 {
public static String reduceString(final String str) {
StringBuffer result = new StringBuffer();
final int count = str.length();
char c1 = str.charAt(0);
int sum = 1;
for (int i = 1; i < count; i++) {
char c2 = str.charAt(i);
if (c1 == c2)
{
sum++;
continue;
}
result.append(c1).append(sum);
c1 = c2;
sum = 1;
}
result.append(c1).append(sum);
return result.toString();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String longStr = sc.next();
System.out.println(reduceString(longStr));
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询