LeetCode 344.反转字符串

问题描述

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

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

问题链接

思路

使用双指针法,left指向s0,right指向ss.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--;
        }
    }
}
相关推荐
All for pursuit.2 小时前
【回溯-6】79.单词搜索
数据结构·c++·算法·leetcode
Navigator_Z2 小时前
LeetCode //C - 1281. Subtract the Product and Sum of Digits of an Integer
c语言·算法·leetcode
旖旎夜光5 小时前
LeetCode 1576: 替换所有的问号(模拟) —— 题解
c++·学习·算法·leetcode·力控
longlongzihan5 小时前
回溯法详解:LeetCode 46. 全排列
算法·leetcode·回溯
圣保罗的大教堂6 小时前
leetcode 3532. 针对图的路径存在性查询 I 中等
leetcode
longlongzihan19 小时前
从LeetCode 70. 爬楼梯看动态规划:如何精准推导状态转移方程?
c++·算法·leetcode·动态规划
Rnan-prince1 天前
LeetCode 股票买卖系列:一个动态规划状态机模板通吃四题
leetcode·动态规划
圣保罗的大教堂1 天前
leetcode 3756. 连接非零数字并乘以其数字和 II 中等
leetcode
All for pursuit.1 天前
【回溯-7】494.目标和
数据结构·c++·算法·leetcode
Tisfy1 天前
LeetCode 0678.有效的括号字符串:O(n)+O(1)一次遍历
算法·leetcode·字符串·题解·贪心·括号匹配