题目:输入一个英文句子,翻转句子中单词的顺序,但单词内字啊的顺序不变。为简单起见,标点符号和普通字母一样处理。
代码如下:
package demo;
/**
* 翻转单词顺序
*
* @author xiangdonglee
*
*/
public class Test42_1 {
/**
* 将data中start到end之间的字符翻转
*
* @param data
* @param start
* @param end
*/
public static void reverse(char[] data, int start, int end) {
if (data == null || data.length < 1 || start < 0 || end > data.length || start > end) {
return;
}
while (start < end) {
char tmp = data[start];
data[start] = data[end];
data[end] = tmp;
start++;
end--;
}
}
/**
* 翻转句子中单词的顺序,但单词内字符顺序不变
*
* @param data
* @return
*/
public static char[] reverseSentence(char[] data) {
if (data == null || data.length < 1) {
return data;
}
reverse(data, 0, data.length - 1);
int start = 0;
int end = 0;
while (start < data.length) {
if (data[start] == ' ') {
start++;
end++;
} else if (end == data.length || data[end] == ' ') {
reverse(data, start, end - 1);
end++;
start = end;
} else {
end++;
}
}
return data;
}
public static void main(String[] args) {
test1();
}
private static void test1() {
System.out.println(new String(reverseSentence("I am a student.".toCharArray())));
System.out.println(new String(reverseSentence("Wonderful".toCharArray())));
System.out.println(new String(reverseSentence("".toCharArray())));
System.out.println(new String(reverseSentence(" ".toCharArray())));
}
}