Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
class Solution(object):
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
return s[::-1]
其他解法:
public class Solution {
public String reverseString(String s) {
byte[] bytes = s.getBytes();
int i = 0;
int j = s.length() - 1;
while (i < j) {
bytes[i] = (byte) (bytes[i] ^ bytes[j]);
bytes[j] = (byte) (bytes[i] ^ bytes[j]);
bytes[i] = (byte) (bytes[i] ^ bytes[j]);
i++;
j--;
}
return new String(bytes);
}
}
用到了交换不用任何空间。
public class Solution {
public String reverseString(String s) {
byte[] bytes = s.getBytes();
int i = 0;
int j = s.length() - 1;
while (i < j) {
byte temp = bytes[i];
bytes[i] = bytes[j];
bytes[j] = temp;
i++;
j--;
}
return new String(bytes);
}
}
class Solution {
public:
string reverseString(string s) {
int i = 0, j = s.size() - 1;
while(i < j){
swap(s[i++], s[j--]);
}
return s;
}
};
标签:return,String,int,bytes,public,344,byte,leetcode From: https://blog.51cto.com/u_11908275/6381147