Problem:
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
public class Solution {
public String reverseString(String s) {
char[] cha = s.toCharArray();
int i = 0;
int j = cha.length-1;
for(; i < j; i++, j--){
char tmp;
tmp = cha[i];
cha[i] = cha[j];
cha[j] = tmp;
}
return new String(cha);
}
}Code2:
public class Solution {
public String reverseString(String s) {
StringBuilder s5 = new StringBuilder(s);
return s5.reverse().toString();
}
}
本文介绍两种在Java中实现字符串反转的方法。第一种方法是通过字符数组的交换来达到反转的效果;第二种方法则是利用StringBuilder类的内置reverse方法实现字符串的反转。

603

被折叠的 条评论
为什么被折叠?



