JZ44-翻转单词序列
翻转单词顺序列
http://www.nowcoder.com/questionTerminal/3194a4f4cf814f63919d0790578d51f3
牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
import java.util.*; public class Solution { public String ReverseSentence(String str) { LinkedList<String> list=new LinkedList<>(); StringBuffer sb = new StringBuffer(); int i=0; while (i<str.length()){ if (str.charAt(i)!=' '){ sb.append(str.charAt(i)); i++; }else { list.addFirst(sb.toString()); sb=new StringBuffer(); i++; } } list.addFirst(sb.toString()); StringBuffer resStr = new StringBuffer(); for (int j = 0; j < list.size(); j++) { if (j!=list.size()-1){ resStr.append(list.get(j)+' '); }else resStr.append(list.get(j)); } // System.out.println(list.getFirst()); // System.out.println(list.getLast()); return resStr.toString(); } }