题目描述
牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
分析:
解题方法与左旋字符串的题异曲同工,就是逆序法:
1.整个句子逆序
2.遍历取得每个单词逆序
具体代码及注释如下:
public class Solution {
public String ReverseSentence(String str) {
char[] c=str.toCharArray();
int len=c.length;
if(len<=1||str==""){return str;}
reverse(c,0,len-1);
int begin=0;
int end=0;
//begin和end前后两个指针遍历数组,得到单词就翻转
while(begin<=end&&end<=len-1){
//遇到空格的情况:两指针同时前进一步
if(c[begin]==' '&&c[end]==' '){
begin++;
end++;
}
//遇到中间单词的时候,end依赖空格判断
else if(c[begin]!=' '&&c[end]==' '){
reverse(c,begin,end-1);
begin=end;
}
//遇到末尾单词的时候,end依赖len-1位置判断
else if(c[begin]!=' '&&end==len-1){
reverse(c,begin,end);
break;
}
//剩下的情况就是begin非空,但end还在单词中间,end继续前进至单词末尾
else{
end++;
}
}
return String.valueOf(c);
}
public void reverse(char[] c,int begin,int end){
while(begin<end){
char temp=c[begin];
c[begin]=c[end];
c[end]=temp;
begin++;
end--;
}
return;
}
}