【2】Reverse String(反转String)

[题目地址]https://leetcode.com/problems/reverse-string/

题目概要:

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

  • 写一个把输入的String反转的方法

思路1:

  • 使用StringBuilder的reverse方法.
public class Solution {
    public String reverseString(String s) {
        return new StringBuilder(s).reverse().toString();
    }
}

思路2:

  • 使用递归的方式:
public class Solution {
    public String reverseString(String s) {
        if (s == null) {
            return s;
        }
        if (s.length() <= 1) {
            return s;
        }
        
        String leftString = s.substring(0, s.length() / 2);
        String rightString = s.substring(s.length() / 2, s.length());
        
        return reverseString(rightString) + reverseString(leftString);
    }
}

你可能感兴趣的:(【2】Reverse String(反转String))