LeetCode 344. Reverse String 原创Java参考解答

LeetCode 344. Reverse String 原创Java参考解答

问题描述

https://leetcode.com/problems/reverse-string/

Write a function that takes a string as input and returns the string reversed.

Example:
Given s = “hello”, return “olleh”.

解题思路

题目求做反转字符串。

这道题有很多做法,这里列举一种简单的做法:单循环字符数组,把第 i 位和倒数第 i 位置交换即可。循环只用到字符串长度的一半位置结束就可以。

参考代码1

public class Solution {
    public String reverseString(String s) {
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length / 2; i++) {
            char temp = chars[chars.length - 1 - i];
            chars[chars.length - 1 - i] = chars[i];
            chars[i] = temp;
        }
        return new String(chars);
    }
}     

参考代码2:递归版本

这道题递归的方法提交会超时。但是面试中面试官往往会在面试者写出非递归的方法后,要求再写一个递归版本方法。所以这里提供递归版本供大家参考。

public class Solution {
    public String reverseString(String s) {
        if (s.length() == 0) {
            return "";
        }
        
        return reverseString(s.substring(1)) + s.charAt(0);
    }
}   

相关题目

LeetCode All in One 原创题目讲解汇总

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注