t题目:牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
参考:https://blog.csdn.net/zl18310999566/article/details/80251679
/** 例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,* 正确的句子应该是“I am a student.”。*/
public class ReverseSentence1 {public static String ReverseSentence(String str) {if(str.isEmpty()||str.length()==0||str==" "){return str;}String [] s=str.split(" ");//I am a student.int start=0;int end=s.length-1;//注意str.length()值为15和s.length 值为4的区别。while(start<end){String temp=s[start];s[start]=s[end];s[end]=temp;start++;end--;}StringBuffer sb = new StringBuffer();for(int i = 0; i < s.length-1; i++){sb. append(s[i]+" ");}sb.append(s[s.length-1]);String s1 = sb.toString();return s1;}public static void main(String[] args) {String result = ReverseSentence(" ");System.out.println(result);}
}
但此方法通过率只有60% ?????????????????