牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
思路:先反转整个句子,再一个个反转单词,靠空格判断单词起始位置
public class Solution {
public String ReverseSentence(String str) {
StringBuffer stringBuffer1 = new StringBuffer(str).reverse();
StringBuffer result = new StringBuffer();
int index = 0;
for (int i = 0;i<stringBuffer1.length();i++){
if(stringBuffer1.charAt(i) == ' '&& i!=(stringBuffer1.length()-1)){
StringBuffer stringBuffer2 = new StringBuffer(stringBuffer1.substring(index,i));
result.append(stringBuffer2.reverse().append(" "));
index = i+1;
}
if (i==(stringBuffer1.length()-1)){
result.append(new StringBuffer(stringBuffer1.substring(index)).reverse());
}
}
return result.toString();
}}