技术算法cpp倒置字符串
chenlei题目链接:倒置字符串__牛客网 (nowcoder.com)
题目描述:
将一句话的单词进行倒置,标点不倒置。比如 I like beijing. 经过函数后变为:beijing. like I
依次输出倒置之后的字符串,以空格分割
输入:
I like beijing.
输出:
beijing. like I
🔓解法一【下标访问】
📖流程描述:
- 整体逆置
reverse(s.begin(), s.end());
- 部分逆置
end遇到’ ‘时,逆置(s.begin()+begin,s.begin()+end)
begin到end的下一位,++end继续遍历,直到s[end] 为0退出循环,完成逆置;
注意:最后一个位置为’\0’时不会逆置,需要在出循环时对最后一个单词逆置

⌨️代码实现:
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 26 27 28
| #include <iostream> #include <string> #include <algorithm> using namespace std;
int main() { string s; int begin = 0, end = 0; getline(cin, s); reverse(s.begin(), s.end()); while (s[end]) { if (s[end] == ' ') { reverse(s.begin() + begin, s.begin() + end); begin = end + 1; } ++end; } reverse(s.begin() + begin, s.begin() + end); cout << s << endl; return 0; }
|
💡解法二【迭代器访问】
📖流程描述:
流程同上,换为迭代器访问更直观简洁
⌨️代码实现:
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 26 27 28
| #include <iostream> #include <string> #include <algorithm> using namespace std;
int main() { string s; getline(cin, s); auto start = s.begin(), end = s.begin(); reverse(s.begin(), s.end()); while (end != s.end()) { if (*end == ' ') { reverse(start, end); start = end + 1; } ++end; } reverse(start, end); cout << s << endl; return 0; }
|
运行结果:
