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.

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"]

在不占用额外内存的情况下,翻转数组.

实现

  • Python
1
2
3
4
5
6
7
8
9
10
11
12
def (self, s) -> None:
"""
O(1)空间复杂度下翻转数组
:param s: List[str]
:return:
"""
lens = len(s)
for i in range(int(lens / 2 )):
print(i)
tmp = s[i]
s[i] = s[lens - i - 1]
s[lens - i - 1] = tmp

讨论区其他答案

  • java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Solution {
public String (String s) {
byte[] bytes = s.getBytes();
int i = 0;
int j = s.length() - 1;
while (i < j) {
bytes[i] = (byte) (bytes[i] ^ bytes[j]);
bytes[j] = (byte) (bytes[i] ^ bytes[j]);
bytes[i] = (byte) (bytes[i] ^ bytes[j]);
i++;
j--;
}
return new String(bytes);
}
}

参考资料