「力扣」第 344 题:反转字符串(简单)

liweiwei1419 ... 2021-12-24 双指针
  • 双指针
About 1 min

# 题目描述

编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。

不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。

示例 1:

输入:["h","e","l","l","o"]
输出:["o","l","l","e","h"]
1
2

示例 2:

输入:["H","a","n","n","a","h"]
输出:["h","a","n","n","a","H"]
1
2

提示:

# 方法一:使用 Java 语言提供的反转 API 完成

参考代码 1

public class Solution {
    public String reverseString(String s) {
        StringBuilder reverse = new StringBuilder();
        for (int i = s.length()-1; i >=0 ; i--) {
            reverse.append(s.charAt(i));
        }
        return reverse.toString();
    }

    // Given s = "hello", return "olleh".
    public static void main(String[] args) {
        String s = "hello";
        Solution solution = new Solution();
        String reverseString = solution.reverseString(s);
        System.out.println(reverseString);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 方法二:使用指针对撞

参考代码 2

Last update: January 13, 2022 07:15
Contributors: liweiwei1419 , suanfa8