问题:
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
解决:
① 使用StringBuilder类的方法。
public class Solution {//3 ms
public String reverseString(String s) {
StringBuilder sb = new StringBuilder(s);
return sb.reverse().toString();
}
}
② 将字符串转换为字符数组,直接翻转即可。
public class Solution {//3 ms
public String reverseString(String s) {
if (s == null) return null;
if (s == "") return "";
char[] schar = s.toCharArray();
int start = 0;
int end = schar.length-1;
while (start < end) {
char temp = schar[start];
schar[start] = schar[end];
schar[end] = temp;
start++;
end--;
}
return new String(schar);
}
}