Write a function that takes a string as input and returns the string reversed.
Example:
Given s = “hello”, return “olleh”.
字符串反转,:
java版本1:
public class Solution {
public String reverseString(String s) {
String res="";
char[] c=s.toCharArray();
for(int i=c.length-1;i>=0;i--){
res=res+c[i];
}
return res;
}
}
版本1会超时,所以使用版本2。思想是从两端向中间移动。
java版本2:
public class Solution {
public String reverseString(String s) {
char[] c=s.toCharArray();
int i=0,j=c.length-1;
while(i<j){
char tmp=c[i];
c[i]=c[j];
c[j]=tmp;
i++;
j--;
}
return new String(c);
}
}
扩展:反转指定的位置,这个时候就要使用3次反转了