Data Structure and Algorithm Compress String 字符串压缩 分析 使用变量 cnt 记录当前字符的连续出现次数; 遍历字符串,统计连续相同字符的个数; 每当遇到下一个字符不同(或到字符串结尾)时,就把当前字符和它的个数拼接到结果字符串中; 最后判断压缩后的结果是否更短,是则返回压缩结果,否则返回原字符串 时间复杂度 时间复杂度 O(n) 空间复杂度 空间复杂度为 O(n) C++代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 class Solution { public: string compressString(string s) { std::string res; // 存储压缩后的字符串 int cnt = 0; // 当前字符的计数 for (int i = 0; i < s.size(); ++ i) { ++cnt; // 如果当前字符是最后一个,或与下一个字符不同,就拼接 if (i + 1 == s.size() || s[i] != s[i + 1]) { res += s[i]; // 添加当前字符 res += std::to_string(cnt); // 添加出现次数 cnt = 0; // 重置计数器 } } // 如果压缩结果更短,返回压缩结果,否则返回原字符串 return res.size() < s.size() ? res : s; } };