题目:牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
思路:
方法一:由题意,可用stack存储单词,出栈后的顺序即为正常顺序。
方法二:先将整个字符串全部翻转,然后再将每个单词翻转即可。
源码:GitHub源码
方法一:
import java.util.*;
public class Solution {
public String ReverseSentence(String str) {
if(str == null || str.trim().equals("")) return str;
Stack<String> stack = new Stack<>();
String[] tmp = str.split(" ");
for(String x : tmp){
stack.push(x);
}
String result = stack.pop();
while(!stack.isEmpty()){
result += " " + stack.pop();
}
return result;
}
}
方法二:
public class Solution {
public String ReverseSentence(String sr) {
if(sr == null || sr.trim().equals("")) return sr;
char[]str = sr.trim().toCharArray();
Reverse(str,0,str.length - 1);
int low = 0;
int high = 0;
while(low != str.length){
if(str[low] == ' '){
low++;
high++;
}else if(str[high] == ' '){
Reverse(str,low,high - 1);//注意:翻转时,空格不动
++high;
low = high;
}else if(high == str.length- 1){
Reverse(str,low,high);
++high;
low = high;
}else{
high++;
}
}
return String.valueOf(str);
}
public void Reverse(char[] str,int start,int end){
while(start <= end){
char tmp = str[start];
str[start] = str[end];
str[end] = tmp;
start++;
end--;
}
}
}