LeetCode 344. Reverse String(反转字符串)

时间:2022-01-10 20:50:09

题目描述

  • LeetCode 344. 反转字符串
  • 请编写一个函数,其功能是将输入的字符串反转过来。

示例

  • 输入: s = "hello"
  • 返回: "olleh"

Java 解答

class Solution {
public String reverseString(String s) {
if (s == null || s.length() <= 1) {
return s;
}
char[] arr = s.toCharArray();
int length = arr.length;
for (int i = 0; i < length / 2; i++) {
char temp = arr[i];
arr[i] = arr[length - i - 1];
arr[length - i - 1] = temp;
}
return String.valueOf(arr); //return new StringBuilder(s).reverse().toString();
}
}