1、题目描述
Write a function that reverses a string. The input string is given as an array of characters char[].
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii characters.
Example 1:
Input: [“h”,“e”,“l”,“l”,“o”]
Output: [“o”,“l”,“l”,“e”,“h”]
Example 2:
Input: [“H”,“a”,“n”,“n”,“a”,“h”]
Output: [“h”,“a”,“n”,“n”,“a”,“H”]
2、不使用任何中间变量交换a,b的值
参考如下代码:
#include<stdio.h>
void swap1(int& a, int& b)
{
int temp = a;
a = b;
b = temp;
}
void swap2(int& a, int& b)
{
a=a+b;
b=a-b;
a=a-b;
}
void swap3(int& a, int& b)
{
a^=b;
b^=a;
a^=b;
}
以上有三个swap函数,都是采用引用传参的方式。
- swap1()显然不是我们需要的
- swap2()采用的是一种简单的加减运算来达到交换a,b的目的,这种方式的缺点是有可能会出现溢出。
- swap3()采用了按位异或的方式交换a,b。相比于swap2(),推荐swap3()。
3、解题思路
这里分两类方法,递归与非递归
3.1、递归解法
解法1:异或交换
class Solution {
public:
void reverseString(vector<char>& s) {
if(!s.empty())
{
helper(s, 0, s.size()-1);
}
}
void helper(vector<char>& s, int left, int right)
{
if(left < right)
{
s[left]^=s[right];
s[right]^=s[left];
s[left]^=s[right];
helper(s, left+1, right-1);
}
}
};
478 / 478 个通过测试用例
状态:通过
执行用时:44 ms
内存消耗:23.4 MB
已经战胜 98.36 % 的 cpp 提交记录
解法二:普通交换
class Solution {
public:
void reverseString(vector<char>& s) {
if(!s.empty())
{
helper(s, 0, s.size()-1);
}
}
void helper(vector<char>& s, int left, int right)
{
if(left < right)
{
char temp = s[left];
s[left] = s[right];
s[right] = temp;
helper(s, left+1, right-1);
}
}
};
478 / 478 个通过测试用例
状态:通过
执行用时:48 ms
内存消耗:23.4 MB
已经战胜 95.70 % 的 cpp 提交记录
3.2、非递归解法
解法一:异或交换
class Solution {
public:
void reverseString(vector<char>& s) {
if(!s.empty())
{
int left = 0;
int right = s.size()-1;
while(left < right)
{
s[left]^=s[right];
s[right]^=s[left];
s[left]^=s[right];
left++;
right--;
}
}
}
};
478 / 478 个通过测试用例
状态:通过
执行用时:44 ms
内存消耗:23.3 MB
已经战胜 98.36 % 的 cpp 提交记录
解法二:普通交换
class Solution {
public:
void reverseString(vector<char>& s) {
if(!s.empty())
{
int left = 0;
int right = s.size()-1;
while(left < right)
{
char temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
}
}
};
478 / 478 个通过测试用例
状态:通过
执行用时:48 ms
内存消耗:23.5 MB
已经战胜 95.70 % 的 cpp 提交记录