LeetCode刷题 - #344 反转字符串

89 阅读1分钟

344. 反转字符串

编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 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"]

答题思路

需要解决的问题:

  • 当前字符与谁交换
  • 怎么交换

方法①数学推导

在数组中,需交换的元素下标之和 = 数组长度 length - 1

i + j = length - 1
j = length - 1 - i

数组不需要全部遍历一遍进行交换,有一个边界值(代入特殊值方法),为数组长度的1/2,超过该值不再遍历交换元素。

方法②双指针

定义两个指针,分别指向数组的头部和尾部,

start = 0; 
end = length - 1

二者进行交换后,再分别向前/后移动,继续交换,直至相遇。

交换方法

private void swap(char[] s, int first, int second) {
    char temp = s[first]; 
    s[first] = s[second]; 
    s[second] = temp; 
}

最终代码

  • 数学推导方法
class Solution {
    public void reverseString(char[] s) {
        if(s == null || s.length == 0) {
            return;
        }
        for(int i = 0; i < s.length / 2; i++) {
            int j = s.length - 1 - i;
            swap(s, i, j);
        }
    }
    private void swap(char[] s, int first, int second) {
        char temp = s[first];
        s[first] = s[second];
        s[second] = temp;
    }
}
  • 双指针方法
class Solution {
    public void reverseString(char[] s) {
        if(s == null || s.length == 0) {
            return;
        }
        int start = 0;
        int end = s.length - 1;
        while(start < end) {
            swap(s, start++, end--);
        }
    }
    private void swap(char[] s, int first, int second) {
        char temp = s[first];
        s[first] = s[second];
        s[second] = temp;
    }
}