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--;
        }
    }
}
相关推荐
Navigator_Z4 小时前
LeetCode //C - 1206. Design Skiplist
c语言·算法·leetcode
码行山野赴时序归途4 小时前
三道经典数组题:从暴力到最优的算法思维
c语言·开发语言·数据结构·算法·leetcode
Navigator_Z6 小时前
LeetCode //C - 1209. Remove All Adjacent Duplicates in String II
c语言·算法·leetcode
土司大王8 小时前
LeetCode hot100——合并两个有序链表
算法·leetcode·链表
wabs66616 小时前
关于栈【力扣1047. 删除字符串中的所有相邻重复项的思考】
数据结构·c++·算法·leetcode··代码随想录
evans在进步18 小时前
LeetCode 53 最大子数组和:一次遍历掌握 Kadane 算法
算法·leetcode·职场和发展
Nil20819 小时前
leetcode 230二叉搜索树中第k小的元素
算法·leetcode·职场和发展
旖旎夜光19 小时前
LeetCode 69:x 的平方根(二分查找) —— 题解
数据结构·c++·算法·leetcode·二分查找
学习星球19 小时前
【LeetCode算法题精讲】图算法精讲——从图遍历到拓扑排序
数据结构·算法·leetcode·图搜索
Nil2081 天前
leetcode 98验证二叉搜索树
算法·leetcode·职场和发展