反转字符串
难度:
标签:
题目描述
编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 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 <= s.length <= 105
s[i]
都是 ASCII 码表中的可打印字符
代码结果
运行时间: 18 ms, 内存: 21.1 MB
/**
* This implementation utilizes Java Streams to reverse an array of characters.
* However, since streams are not directly suitable for in-place modification,
* we first convert the character array to a List, reverse the List, and then convert it back.
* Note: This method uses extra space due to conversion between List and array.
*/
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Solution {
public void reverseString(char[] s) {
// Convert array to list
List<Character> list = Arrays.asList(toCharacterArray(s));
// Reverse the list
Collections.reverse(list);
// Convert list back to array
for (int i = 0; i < list.size(); i++) {
s[i] = list.get(i);
}
}
private Character[] toCharacterArray(char[] s) {
Character[] charObjectArray = new Character[s.length];
for (int i = 0; i < s.length; i++) {
charObjectArray[i] = s[i];
}
return charObjectArray;
}
}
解释
方法:
这个题解采用了双指针的思路。定义两个指针分别指向字符串的起点和终点,然后不断交换两个指针指向的字符,同时将两个指针向中间移动,直到两个指针相遇。这样就实现了反转字符串的目的。
时间复杂度:
O(n)
空间复杂度:
O(1)
代码细节讲解
🦆
为什么选择使用双指针方法来解决字符串反转的问题?有没有其他可能的方法?
▷🦆
在双指针方法中,使用负索引`-i-1`来访问数组的尾部元素是如何工作的?具体是怎样计算出对应的索引位置?
▷🦆
双指针交换字符的过程中,是否需要担心出现越界错误?如果需要,如何确保在交换过程中不会发生越界?
▷🦆
这种原地反转的方法是否适用于所有类型的字符数组,包括包含特殊字符或Unicode字符的数组?
▷