解题思路
这是一道字符串压缩题目,主要思路如下:
-
问题分析:
- 输入一个字符串
- 连续重复的字符需要压缩
- 如果重复次数为1则不需要写数字
- 输出压缩后的字符串
-
解决方案:
- 遍历字符串
- 统计连续相同字符的个数
- 当字符改变时输出压缩结果
- 特殊处理最后一组字符
-
实现细节:
- 使用双指针或计数器
- 注意处理边界情况
- 考虑单个字符的情况
代码
#include <iostream>
#include <string>
using namespace std;
string compress(string s) {
if(s.empty()) return "";
string result;
int count = 0;
char current = s[0];
// 遍历字符串
for(int i = 1; i <= s.length(); i++) {
// 当前字符与前一个相同
if(i < s.length() && s[i] == current) {
count++;
}
// 当前字符与前一个不同或到达字符串末尾
else {
// 只有count>=1时才添加数字
if(count >= 1) {
result += to_string(count);
}
result += current;
// 更新当前字符和计数
if(i < s.length()) {
current = s[i];
count = 0;
}
}
}
return result;
}
int main() {
string s;
getline(cin, s);
cout << compress(s) << endl;
return 0;
}
import java.util.Scanner;
public class Main {
public static String compress(String s) {
if(s == null || s.isEmpty()) return "";
StringBuilder result = new StringBuilder();
int count = 0;
char current = s.charAt(0);
for(int i = 1; i <= s.length(); i++) {
if(i < s.length() && s.charAt(i) == current) {
count++;
} else {
if(count >= 1) {
result.append(count);
}
result.append(current);
if(i < s.length()) {
current = s.charAt(i);
count = 0;
}
}
}
return result.toString();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
System.out.println(compress(s));
}
}
def compress(s: str) -> str:
if not s:
return ""
result = []
count = 0
current = s[0]
# 遍历字符串
for i in range(1, len(s) + 1):
# 当前字符与前一个相同
if i < len(s) and s[i] == current:
count += 1
# 当前字符与前一个不同或到达字符串末尾
else:
# 只有count>=1时才添加数字
if count >= 1:
result.append(str(count))
result.append(current)
# 更新当前字符和计数
if i < len(s):
current = s[i]
count = 0
return ''.join(result)
def main():
s = input().strip()
print(compress(s))
if __name__ == "__main__":
main()
算法及复杂度
- 算法:字符串遍历
- 时间复杂度:
-
为字符串长度
- 空间复杂度:
- 最坏情况下需要存储原始字符串长度的结果