LeetCode 344.反转字符串

问题描述

编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 s 的形式给出。

不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题

问题链接

思路

使用双指针法,left指向s[0],right指向s[s.length - 1];两指针相向遍历数组,每次交换两位置的字符,直到两指针相遇

code

java 复制代码
class Solution {
    public void reverseString(char[] s) {
        int left = 0;
        int right = s.length - 1;
        //当left与right不相等时,交换left和right处的字符
        while(left <= right){
            char temp = s[left];
            s[left] = s[right];
            s[right] = temp;
            left++;
            right--;
        }
    }
}
java 复制代码
class Solution {

    public void reverseString2(char[] s) {
        int left = 0;
        int right = s.length - 1;
        while (left < right){
            s[left] ^= s[right]; //构造 a ^ b 的结果,并放在 a 中
            s[right] ^= s[left]; //将 a ^ b 这一结果再 ^ b ,存入b中,此时 b = a, a = a ^ b
            s[left] ^= s[right];  //a ^ b 的结果再 ^ a ,存入 a 中,此时 b = a, a = b 完成交换
            left++;
            right--;
        }
    }
}
相关推荐
hn小菜鸡7 小时前
LeetCode 377.组合总和IV
数据结构·算法·leetcode
亮亮爱刷题10 天前
飞往大厂梦之算法提升-7
数据结构·算法·leetcode·动态规划
zmuy10 天前
124. 二叉树中的最大路径和
数据结构·算法·leetcode
chao_78910 天前
滑动窗口题解——找到字符串中所有字母异位词【LeetCode】
数据结构·算法·leetcode
Alfred king10 天前
面试150跳跃游戏
python·leetcode·游戏·贪心算法
呆呆的小鳄鱼10 天前
leetcode:746. 使用最小花费爬楼梯
算法·leetcode·职场和发展
YuTaoShao10 天前
【LeetCode 热题 100】42. 接雨水——(解法一)前后缀分解
java·算法·leetcode·职场和发展
YuforiaCode10 天前
(LeetCode 面试经典 150 题) 27.移除元素
算法·leetcode·面试
呆呆的小鳄鱼10 天前
leetcode:98. 验证二叉搜索树
算法·leetcode·职场和发展
alphaTao10 天前
LeetCode 每日一题 2025/6/16-2025/6/22
算法·leetcode