344.Reverse String
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = “hello”, return “olleh”.
思路:字符串反转输出。转换成char[]遍历逆序后转回String输出
代码如下:
/**
* Created by Poldi on 2017/7/7.
*/
public class ReverseString {
public String reverseString(String s) {
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length/2; i++) {
char temp = chars[i];
chars[i] = chars[chars.length-1-i];
chars[chars.length-1-i] = temp;
}
return String.valueOf(chars);
}
public static void main(String[] args) {
ReverseString reverseString = new ReverseString();
System.out.println(reverseString.reverseString("hello"));
}
}
也可以利用StringBuilder的reverse()直接逆序
代码如下:
public String reverseString(String s) {
StringBuilder sb = new StringBuilder(s);
return sb.reverse().toString();
}