Question:
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
Code:
Here is Java:
public class Solution {
public String reverseString(String s) {
StringBuffer buffer = new StringBuffer();
if(s==null || s.isEmpty()) return s ;
for(int i=s.length()-1; i>=0; i--){
buffer.append(s.charAt(i));
}
return buffer.toString();
}
}
// 两边一起走自然是更快的
public class Solution {
public String reverseString(String s) {
if(s==null || s.isEmpty()) return s ;
int left = 0 ;
int right = s.length()-1;
char[] array = s.toCharArray() ;
while(left<right){
char temp = array[left] ;
array[left++] = array[right];
array[right--] = temp ;
}
return String.valueOf(array);
}
}
// stringBuffer and StringBuild maybe a better answer
public class Solution {
public String reverseString(String s) {
StringBuffer() sb = new StringBuffer(s);
return s.reverse().toString();
}
}
And JS
/**
* @param {string} s
* @return {string}
*/
var reverseString = function(s) {
return s.split("").reverse().join("") ;
};
python 大法好
class Solution(object):
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
return s[::-1]