/**
* 题目:颠倒一个句子中的词的顺序。比如: I am a student颠倒后变成:student a am I.词以空格分隔。 要求:
* 1.实现速度最快,移动最少 2.不能使用String的方法如split,indexOf等等。 解答:两次翻转。
*/
public class ReverseWords {
public static void main(String[] args) {
String str = "i am so busy now ";
str = reverseWords(str);
System.out.println(str);
}
public static String reverseWords(String str) {
if (str == null) {
return null;
}
int length;
if ((length = str.length()) == 0 || length == 1) {
return str;
}
char[] letters = str.toCharArray();
int begin = -1;
int end = -1;
boolean hasBegined = false;
boolean hasEnded = false;
for (int i = 0, len = str.length(); i < len - 1; i++) {
if (letters[i] != ‘ ‘) {
if (!hasBegined) {
begin = i;
hasBegined = true;
} else {
if (letters[i + 1] == ‘ ‘) {
end = i;
hasEnded = true;
}
if (i == len - 2 && letters[i + 1] != ‘ ‘) {
end = i + 1;
hasEnded = true;
}
if (hasEnded) {
reverseOneWord(letters, begin, end);
hasBegined = false;
hasEnded = false;
}
}
}
}
reverseOneWord(letters, 0, str.length() - 1);
return new String(letters, 0, str.length());
}
public static void reverseOneWord(char[] letters, int begin, int end) {
if (letters == null || letters.length < 2) {
return;
}
int len = letters.length;
if (begin >= 0 && begin < len && end >= 0 && end < len) {
while (begin < end) {
char tmp = letters[begin];
letters[begin] = letters[end];
letters[end] = tmp;
begin++;
end--;
}
}
}
}
java-颠倒一个句子中的词的顺序。比如: I am a student颠倒后变成:student a am I,布布扣,bubuko.com