题目描述
字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaaa
会变为a2b1c5a3
。若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a至z)。
示例1:
输入:"aabcccccaaa" 输出:"a2b1c5a3"
示例2:
输入:"abbccd" 输出:"abbccd" 解释:"abbccd"压缩后为"a1b2c2d1",比原字符串长度更长。
提示:
- 字符串长度在[0, 50000]范围内。
思路
代码
#include <iostream>
#include <string>
using namespace std;
class Solution {//O(N) O(1)
public:
string compressString(string S) {
if ((int)S.length() == 0) return S; // 空串处理
string ans = "";
int cnt = 1;
char ch = S[0];
for (int i = 1; i < (int)S.length(); ++i) {
if (ch == S[i]) cnt++;
else {
ans += ch + to_string(cnt); // 注意 cnt 要转为字符串
ch = S[i];
cnt = 1;
}
}
ans += ch + to_string(cnt);
return ans.length() >= S.length() ? S : ans;
}
};
int main() {//aabcccccaa
string input;
getline(cin, input);
string ans;
Solution a;
cout << a.compressString(input) << endl;
}
变形题
给你一个字符数组 chars
,请使用下述算法压缩:
从一个空字符串 s
开始。对于 chars
中的每组 连续重复字符 :
- 如果这一组长度为
1
,则将字符追加到s
中。 - 否则,需要向
s
追加字符,后跟这一组的长度。
压缩后得到的字符串 s
不应该直接返回 ,需要转储到字符数组 chars
中。需要注意的是,如果组长度为 10
或 10
以上,则在 chars
数组中会被拆分为多个字符。
请在 修改完输入数组后 ,返回该数组的新长度。
你必须设计并实现一个只使用常量额外空间的算法来解决此问题。
示例 1:
输入:chars = ["a","a","b","b","c","c","c"] 输出:返回 6 ,输入数组的前 6 个字符应该是:["a","2","b","2","c","3"] 解释:"aa" 被 "a2" 替代。"bb" 被 "b2" 替代。"ccc" 被 "c3" 替代。
代码
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution1 {
public:
int compress(vector<string>& chars) {
int n = chars.size();
int write = 0, left = 0;
for (int read = 0; read < n; read++) {
if (read == n - 1 || chars[read] != chars[read + 1]) {
chars[write++] = chars[read];
int num = read - left + 1;
if (num > 1) {
int anchor = write;
while (num > 0) {
chars[write++] = num % 10 + '0';
num /= 10;
}
reverse(&chars[anchor], &chars[write]);
}
left = read + 1;
}
}
return write;
}
};
vector<string> split_str(string params_str) {
vector<string> p;
while (params_str.find(",") != string::npos) {
int found = params_str.find(",");
p.push_back((params_str.substr(0, found)));
params_str = params_str.substr(found + 1);
}
p.push_back((params_str));
return p;
}
int main() {//a,a,b,b,c,c,c
string input;
getline(cin, input);
vector<string> lst;
lst = split_str(input);
Solution1 a;
int ans;
ans = a.compress(lst);
cout << ans;
}