该文已加入开源项目:LeetCodeAnimation(用动画的形式呈现解LeetCode题目的思路,目前 8500 Star )。地址:https://github.com/MisterBooo/LeetCodeAnimation
LeetCode上第 344 号问题:Reverse String
编写一个函数,其作用是将输入的字符串反转过来。
示例 1:
输入: "hello" 输出: "olleh"
示例 2:
输入: "A man, a plan, a canal: Panama" 输出: "amanaP :lanac a ,nalp a ,nam A"
直接从两头往中间走,同时交换两边的字符即可
动画演示
1// 344. Reverse String
2// https://leetcode.com/problems/reverse-string/description/
3// Two Pointers
4// 时间复杂度: O(n)
5// 空间复杂度: O(1)
6class Solution {
7public:
8 string reverseString(string s) {
9
10 int i = 0, j = s.size() - 1;
11 while(i < j){
12 swap(s[i], s[j]);
13 i ++;
14 j --;
15 }
16
17 return s;
18 }
19};
代码截图
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有