【LeetCode】344、反转字符串

344、Reverse String反转字符串

难度:简单

题目描述

  • 英文:

    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.

  • 中文:

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

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

    你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。

  • 示例

    Example 1:

    1
    2
    Input: ["h","e","l","l","o"]
    Output: ["o","l","l","e","h"]

    Example 2:

    1
    2
    Input: ["H","a","n","n","a","h"]
    Output: ["h","a","n","n","a","H"]

解题思路

思路一

递归思路,不使用额外空间,从首尾两端开始交换字符,并依次向内部缩小,直至交换到数组中间位置时结束。

用$s[x_i,…,x_j]$表示字符数组,其中$x_i , x_j$表示数组中的字符内容,$i,j$为对应的位置,则:

代码提交

C++,用时60ms,内存19M

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
void swap(vector<char>& s, int left, int right) {
if (left >= right) {
return;
}
char temp = s[left];
s[left] = s[right];
s[right] = temp;
swap(s, left+1, right-1);
return;
}

void reverseString(vector<char>& s) {
if (s.size() <= 1)
return;
swap(s, 0, s.size()-1);
return;
}
};

进行Recursion探索时完成的,其他解法后续补充。

-------------本文结束感谢您的阅读-------------
0%