劍指offer-44:翻轉單詞順序列
阿新 • • 發佈:2018-12-18
題目描述
牛客最近來了一個新員工Fish,每天早晨總是會拿著一本英文雜誌,寫些句子在本子上。同事Cat對Fish寫的內容頗感興趣,有一天他向Fish借來翻看,但卻讀不懂它的意思。例如,“student. a am I”。後來才意識到,這傢伙原來把句子單詞的順序翻轉了,正確的句子應該是“I am a student.”。Cat對一一的翻轉這些單詞順序可不在行,你能幫助他麼?
思路
先翻轉整體,在翻轉單詞。
程式碼
public class Solution44 {
public String ReverseSentence(String str) {
char [] chars = str.toCharArray();
int len = chars.length;
reverse(chars, 0, len - 1);
int start = 0, end = 0;
while (start < len) {
if (chars[start] == ' ') {
start++;
end++;
} else if (end == len || chars[end] == ' ' ) {
reverse(chars, start, --end);
start = ++end;
} else {
end++;
}
}
return new String(chars);
}
public void reverse(char[] chars, int low, int high) {
while (low < high) {
char temp = chars[low];
chars[low] = chars[high];
chars[high] = temp;
low++;
high--;
}
}
public static void main(String[] args) {
BeanUtil.print(new Solution44().ReverseSentence("student. a am I "));
}
}