java 输入字符串str如“ABBCCCCAA”,则输出的结果是A1B2C4A2
时间: 2024-03-23 19:36:24 浏览: 11
好的,这是一个Java实现的示例代码:
```java
public static String compressStr(String inputStr) {
if (inputStr == null || inputStr.isEmpty()) {
return "";
}
StringBuilder compressedStr = new StringBuilder();
char currentChar = inputStr.charAt(0);
int charCount = 0;
for (int i = 0; i < inputStr.length(); i++) {
char ch = inputStr.charAt(i);
if (ch == currentChar) {
charCount++;
} else {
compressedStr.append(currentChar).append(charCount);
currentChar = ch;
charCount = 1;
}
}
// Add the last character to the compressed string
compressedStr.append(currentChar).append(charCount);
return compressedStr.toString();
}
```
你可以将需要压缩的字符串传递给`compressStr`函数,它将返回压缩后的字符串。例如,对于输入字符串`"ABBCCCCAA"`,函数将返回`"A1B2C4A2"`。