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--;
        }
    }
}
相关推荐
Swift社区3 小时前
LeetCode 401 - 二进制手表
算法·leetcode·ssh
派大星爱吃猫3 小时前
顺序表算法题(LeetCode)
算法·leetcode·职场和发展
Pluchon10 小时前
硅基计划4.0 算法 二叉树深搜(DFS)
java·数据结构·算法·leetcode·深度优先·剪枝
sprintzer11 小时前
10.6-10.15力扣模拟刷题
算法·leetcode·职场和发展
一匹电信狗12 小时前
【C++】C++风格的类型转换
服务器·开发语言·c++·leetcode·小程序·stl·visual studio
学学学无无止境13 小时前
力扣-上升的温度
leetcode
Emilia486.15 小时前
【Leetcode&nowcode&数据结构】顺序表的应用
数据结构·算法·leetcode
Dream it possible!16 小时前
LeetCode 面试经典 150_栈_简化路径(53_71_C++_中等)(栈+stringstream)
c++·leetcode·面试·
程序员阿鹏16 小时前
49.字母异位词分组
java·开发语言·leetcode
Espresso Macchiato17 小时前
Leetcode 3715. Sum of Perfect Square Ancestors
算法·leetcode·职场和发展·leetcode hard·树的遍历·leetcode 3715·leetcode周赛471