Description
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = “hello”, return “olleh”.
解法1
第一时间想起了stack,于是写了如下代码,可是提示Time Limit Exceeded~~~
public String reverseString(String s) {
String res = "";
Stack<Character> stack = new Stack<>();
char[] ch = s.toCharArray();
int count = 0;
for(char c : ch) {
count++;
stack.push(c);
}
for(int i=0; i<count;i++) {
res += stack.pop();
}
return res;
}
解法2
直接用StringBuffer的reverse()方法。
public String reverseString1(String s) {
return new StringBuffer(s).reverse().toString();
}
解法3
调换s的第一位和最后一位,第二位和倒数第二位……..
public String reverseString2(String s) {
char[] word = s.toCharArray();
int i = 0, j = word.length -1;
while(i<j) {
char tmp = word[i];
word[i] = word[j];
word[j] = tmp;
i++;
j--;
}
return new String(word);
}
第五六七行 word[i]和word[j]对换位置可以替换为:
word[i] = (char) (word[i] ^ word[j]);
word[j] = (char) (word[i] ^ word[j]);
word[i] = (char) (word[i] ^ word[j]);