01 題目描述
輸入一個(gè)英文句子,翻轉(zhuǎn)句子中單詞的順序,但單詞內(nèi)字符的順序不變。為簡(jiǎn)單起見(jiàn)標(biāo)點(diǎn)符號(hào)和普通字母一樣處理。例如輸入字符串"I am a student." 翻轉(zhuǎn)后是"student. a am I"
02 解題
這道題我們可以分兩步,第一步翻轉(zhuǎn)所以字符的順序如:I am a student. 翻轉(zhuǎn)為 .tnedut a ma i。第二步,將每個(gè)單詞中的所有字符翻轉(zhuǎn),結(jié)果為 student. a am i。
翻轉(zhuǎn)數(shù)組實(shí)現(xiàn):一個(gè)首指針start=0,尾指針end=arrays.length-1。分別指向字符串?dāng)?shù)組的頭和尾。交換start和end所在位置的值。之后start++,end--;直到start >= end;
翻轉(zhuǎn)代碼
public static void reverse(char[] chars, int start, int end) {
while (start < end) {
char tmp = chars[start];
chars[start] = chars[end];
chars[end] = tmp;
start ++;
end --;
}
}
第二步:翻轉(zhuǎn)單詞內(nèi)部順序
如 .tnedut a ma i。
記start=0,end=0;end++ 到下一個(gè)空格end=6,翻轉(zhuǎn) start 到end-1的值,
之后進(jìn)入下一個(gè)單詞 end++; start=end;end繼續(xù)遍歷到空格,翻轉(zhuǎn)start到end-1的值。直到最后一個(gè)單詞
public static char[] reversewords(char []words) {
if (words == null || words.length == 0) {
return null;
}
int start = 0, end = 0;
reverse(words, start, words.length - 1); // 1. 翻轉(zhuǎn)整個(gè)數(shù)組
while (end < words.length) {
if (words[end] != ' ') {
end ++;
} else {
reverse(words, start, end - 1);
end ++;
start = end;
}
}
System.out.println(words);
return words;
}






