将字符串i am biter 逆置为:biter am i
第一张方法:
public class TestDemo3 {
public static String reverseSentence(String str) {
char[] a = str.toCharArray();
char[] b = new char[a.length];
int len = a.length;
for (int i = 0; i < len; i++) {
b[len - 1 - i] = a[i];
}
int count = 0;
char[] c = b.clone();
for (int i = 0; i < b.length; i++) {
if (b[i] !=' ') {
count++;
} else {
int k = 0;
for (int j = i - count; j < i; j++) {
if (k < count) {
c[j] = b[i - 1 - k];
k++;
}
}
count = 0;
}
}
String d = new String(c);
return d;
}
public static void main(String[] args) {
System.out.println(reverseSentence("i am biter"));
}
}
第二种方法:
public static void reverse(char[]str,int left,int right){
while(left<right){
char temp = str[left];
str[left] = str[right];
str[right] = temp;
left++;
right--;
}
}
public static String reverseSentence(String str) {
char[] chars= str.toCharArray();
reverse(chars,0,str.length()-1);
int i = 0;
int j = 0;
while(i <chars.length){
if(chars[i]==' '){
i++;
j++;
}else if(j == str.length()||chars[j]==' '){
reverse(chars,i,--j);
i = ++ j;
}else{
j++;
}
}
return String.copyValueOf(chars);
}
public static void main(String[] args) {
System.out.println(reverseSentence("i am biter"));
}
}