题目:
Write a function that reverses a string. The input string is given as an array of characters s.
写一个反转字符串的函数。输入字符串以字符数组的形式给出。
Example 1:
Input: s = [“h”,“e”,“l”,“l”,“o”] Output: [“o”,“l”,“l”,“e”,“h”]
示例 1:
输入:[“h”,“e”,“l”,“l”,“o”] 输出:[“o”,“l”,“l”,“e”,“h”]
Example 2:
Input: s = [“H”,“a”,“n”,“n”,“a”,“h”] Output: [“h”,“a”,“n”,“n”,“a”,“H”]
示例 2:
输入:[“H”,“a”,“n”,“n”,“a”,“h”] 输出:[“h”,“a”,“n”,“n”,“a”,“H”]
Constraints:
1 <= s.length <=
1
0
5
10^5
105 s[i] is a printable ascii character.
提示:
1 <= s.length <=
1
0
5
10^5
105 s[i] 是可打印的ASCII字符.
Follow up:
Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.
进阶:
不要为其他数组分配额外的空间。为此,必须使用O(1)额外内存就地修改输入数组。
解题思路:
方法:双指针
观察给出的示例,得出当n为字符数组长度时s[i]的字符与s[n-1-i]的字符互换了。我们定义left指向字符数组的第一个元素,right指向字符数组的最后一个元素。当left<right时:s[left]和s[right]进行交换且left右移一位、right左移一位。当left>=right时,结束返回字符数组。
Python代码
class Solution:
def reverseString(self, s: List[str]) -> None:
left, right = 0, len(s) - 1
while(left < right):
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
Java代码
class Solution {
public void reverseString(char[] s) {
int n = s.length;
for (int left = 0, right = n - 1; left < right; ++left, --right) {
char temp = s[left];
s[left] = s[right];
s[right] = temp;
}
}
}
C++代码
class Solution {
public:
void reverseString(vector<char>& s) {
int n = s.size();
for (int left = 0, right = n - 1; left < right; ++left, --right) {
swap(s[left], s[right]);
}
}
};
复杂度分析
时间复杂度:O(N),其中 n为字符数组的长度。进行了 n/2次的交换。 空间复杂度:O(1)。只需常数空间存放若干变量。
|