算法 Java Leetcode

Takes a string as input and returns the string reversed.

Question

Write a function that takes a string as input and returns the string reversed.
See it on Leetcode

1
Example: Given s = "hello", return "olleh".

Hint

Should pay attention to the null parameter judgement.

Solution

  • java
  • cpp
1
2
3
4
5
6
7
8
9
10
public class Solution {
public String reverseString(String s) {
char[] chars = new char[s.length()];
int index = 0;
for (int i = s.length() - 1; i >= 0; i--) {
chars[index++] = s.charAt(i);
}
return new String(chars);
}
}