1 条题解
-
0
【例69.1】 过滤多余的空格
解题思路
遍历原句,非空格直接保留,空格仅当结果末尾不是空格时追加。这样每段连续空格只保留首个。
正确性说明
依题目给出的对应关系逐项处理,位置与原输入保持明确对应。每一步完成当前项的全部贡献,结束后得到所有位置或字符的目标结果。
易错点
不能删掉所有空格;头尾保证无空格。
复杂度
时间O(L),空间O(L)。
参考代码(C++11)
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); string s, t; getline(cin, s); for (char c : s) if (c != ' ' || t.empty() || t.back() != ' ') t += c; cout << t << "\n"; return 0; }
- 1