package common;
/**
* @author : zhaoliang
* @program :newCoder
* @description : 翻转单词序列
* @create : 2020/12/13 19:19
*/
public class ReverseSentence {
//牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,
//有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。
//后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
public String ReverseSentence(String str){
int n = str.length();
char[] chars = str.toCharArray();
int i=0,j=0;
while (j <=n){
if (j == n || chars[j] == ' '){
reverse(i,j-1,chars);
i = j+1;
}
j++;
}
reverse(0,n-1,chars);
return new String(chars);
}
private void reverse(int i, int j, char[] chars) {
while (i < j){
swap(i++,j--,chars);
}
}
private void swap(int i, int j, char[] chars) {
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
}
03-25
3万+