Reverse String
Write a function that takes a string as input and returns the string reversed.
Given s = "hello", return "olleh".
1. Use built-in reverse function.
2. Reverse it by a loop.
class Solution {
public String reverseString(String s) {
if (s == null || s.length() == 0) {
return s;
}
int len = s.length();
StringBuilder builder = new StringBuilder();
for (int i = len - 1; i >= 0; i--) {
builder.append(s.charAt(i));
}
return builder.toString();
}
}
class Solution {
public:
string reverseString(string s) {
int len = s.length();
if (len == 0) {
return s;
}
string reverse;
for (int i = len - 1; i >= 0; i--) {
reverse += s[i];
}
return reverse;
}
};
class Solution(object):
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
if s == None or len(s) == 0:
return s
return s[::-1]
- Time Complexity: O(N), N is the length of the input string
- Space Complexity: O(N), N is the length of the input string