单词反转问题
“hello world” —–> “world hello”
输入:字符数组
输出:反转后的字符串
思路:
先将整个字符数组反转,然后根据空格来确定各个单词的起始位置并单独进行反转。
代码如下:
import java.util.Arrays;
/**
* Created by Administrator on 2017/9/12.
* 翻转单词 如“hello world”翻转为“world hello”
*
*/
public class Reverse {
public static void reverse(char []a){
if(a.length == 0 || a == null) return;
int beg = 0;
int end = a.length-1;
reverse_word(a,beg,end);//先反转整个字符数组
beg = -1;
end = -1;
for (int i = 0; i < a.length; i++) {
//单词开始位置
if (beg == -1 && a[i] != ' '){
beg = i;
continue;
}
//单词结束位置的后一位
if (beg != -1 && a[i] == ' '){
end = i - 1;
reverse_word(a,beg,end);
beg = -1;
end = -1;
continue;
}
//字符串数组结尾位置
if (beg != -1 && i == a.length - 1){
end = i;
reverse_word(a,beg,end);
break;
}
}
String s = String.valueOf(a);
System.out.println(s);
}
public static void reverse_word(char []a,int beg,int end){
while(beg < end){
char tem = a[beg];
a[beg] = a[end];
a[end] = tem;
beg++;
end --;
}
}
public static void main(String args[]){
String s = "hello world ";
char []a = s.toCharArray();
reverse(a);
}
}