-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReverseString.java
50 lines (44 loc) · 1.48 KB
/
ReverseString.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package leetcode.two_pointers;
/**
* @description 344. 反转字符串
* @author chengzw
* @link https://leetcode.cn/problems/reverse-string/
* <p>
* 编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 s 的形式给出。
* 不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。
* <p>
* 示例 1:
* 输入:s = ["h","e","l","l","o"]
* 输出:["o","l","l","e","h"]
* <p>
* 示例 2:
* 输入:s = ["H","a","n","n","a","h"]
* 输出:["h","a","n","n","a","H"]
* @since 2022/6/6
*/
/**
编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 s 的形式给出。
不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。
示例 1:
输入:s = ["h","e","l","l","o"]
输出:["o","l","l","e","h"]
示例 2:
输入:s = ["H","a","n","n","a","h"]
输出:["h","a","n","n","a","H"]
*/
/**
思路:双指针
1.指针 left 从左往右遍历,指针 right 从右往左遍历
2.交换 left 和 right 的元素
时间复杂度:O(n)
空间复杂度:O(1)
*/
public class ReverseString {
public void reverseString(char[] s) {
for (int left = 0, right = s.length - 1; left < right; left++, right--) {
char tmp = s[left];
s[left] = s[right];
s[right] = tmp;
}
}
}