LeetCode 344. Reverse String
Description
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = “hello”, return “olleh”.
class Solution {
public String reverseString(String s) {
char[] str = s.toCharArray();
int h = s.length() - 1;
int l = 0;
while (l < h) {
char tmp = str[l];
str[l] = str[h];
str[h] = tmp;
l++;
h--;
}
return new String(str);
}
}
Complexity Analysis
Time Complexity: O(n)
(Average Case) and O(n)
(Worst Case) where n
is the total number character in the input string. The algorithm need to reverse the whole string.
Auxiliary Space: O(n)
space is used where n
is the total number character in the input string. Space is needed to transform string to character array.