C++学习记录-旧题新做-字符串压缩

旧题记录帖:https://blog.csdn.net/chamao_/article/details/143305269?fromshare=blogdetail&sharetype=blogdetail&sharerId=143305269&sharerefer=PC&sharesource=chamao_&sharefrom=from_link

c++解法:

cpp 复制代码
class Solution {
public:
    string compressString(string S) {
        if(S.empty()) return S;
        std::string s;
        s.reserve(S.length() * 2); // .reserve()能提前预留空间
        int index = 0;
        int i = 0;
        while(i < S.length()) {
            char currentChar = S[i];
            int count = 0;
            while(i < S.length() && S[i] == currentChar) {
                count++;
                i++;
            }
            // 追加字符和数字
            s += currentChar;
            s += std::to_string(count);
        }
        if(s.length() >= S.length()) {
            return S;
        }
        return s;
    }
};

1. 为什么用.reserve() 而不是 .resize()?

  • reserve(n):只是提前分配"容量",不改变字符串长度

  • resize(n):改变字符串的"长度",并用 '\0' 填充新增字符

在我的压缩字符串构造过程中,我并不希望字符串一开始就变长 ,所以要用 reserve

2. std::to_string 是什么?

to_string() 用来把"数字类型"转换为 std::string

例如:

cpp 复制代码
std::string s = std::to_string(123);   // "123"

std::string s = std::to_string(123); // "123"

这是 C++11 新增的功能。


3. to_string 支持哪些类型?

它支持 基本数字类型

类型 示例
int std::to_string(10)
long std::to_string(123L)
long long std::to_string(123LL)
unsigned std::to_string(10u)
unsigned long std::to_string(10ul)
unsigned long long std::to_string(10ull)
float std::to_string(3.14f)
double std::to_string(3.14)
long double std::to_string(3.14L)

📌 注意:不支持 char 和 bool!

如果你写:

cpp 复制代码
std::to_string('A');

std::to_string('A');

它会把 'A' 当做数字 65 转换成 "65"


4. 为什么 C++ 推荐用 to_string 而不是 sprintf

因为它更安全、更直观:

✔ 不需要格式化字符串

sprintf 写错一个 %d%s 会崩溃。

to_string 不会。

✔ 无需关心缓冲区大小

sprintf 必须让你自己保证 buffer 足够大。

to_string 会自动管理内存,完全不会溢出。

对比:

cpp 复制代码
char buf[20];
sprintf(buf, "%d", num);   // 危险,需检查大小

char buf[20]; sprintf(buf, "%d", num); // 危险,需检查大小

C++ 写法:

cpp 复制代码
std::string s = std::to_string(num);

std::string s = std::to_string(num);

一行解决。

相关推荐
JieE2129 小时前
LeetCode 56. 合并区间|超清晰 JS 图解思路,面试高频区间题
javascript·算法·面试
Jack2016 小时前
HarmonyOS开发中错误处理策略:网络异常统一处理
算法
小小杨树18 小时前
读懂色彩:拍照调色不再难
算法·计算机视觉·配色
JieE2121 天前
LeetCode 226. 翻转二叉树|JS 递归超详细拆解,二叉树入门经典题
javascript·算法
JieE2121 天前
LeetCode 104. 二叉树的最大深度|递归思路超详细拆解
javascript·算法
vivo互联网技术2 天前
CVPR 2026 | 全新强化学习框架 BeautyGRPO:重塑真实人像
算法·大模型·cvpr·影像
Darling噜啦啦2 天前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
clint4562 天前
C++进阶(1)——前景提要
c++
用户497863050732 天前
(一)小红的数组操作
算法·编程语言