剑指offer--翻转单词顺序列

来源:互联网 发布:anywhere2 mac 蓝牙 编辑:程序博客网 时间:2024/05/20 15:38

牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?



public class 翻转单词顺序列 {public static void main(String[] args) {// TODO Auto-generated method stubString output = new String("I am a student.");//String output = new String(" ");output = ReverseSentence(output);System.out.println(output);}    public static String ReverseSentence(String str) {    if (str==null) {return str;}        if(str.trim().equals("")){//返回一个没有前导和尾部空白的字符串            return str;        }    str = Reverseword(str);    String[] temp = str.split(" ");StringBuffer answer = new StringBuffer();for (int i = 0; i < temp.length; i++) {temp[i]=Reverseword(temp[i]);if (i==temp.length-1) {answer.append(temp[i]);}else {answer.append(temp[i]+" ");}}return answer.toString();    }            /**     * @param str输入一个字符串单词     * @return 返回反转后的单词;     */    public static String Reverseword(String str) {    if (str==null) {return str;}    char[] temp = str.toCharArray();    int begin = 0;    int end = str.length()-1;    while (begin<end) {char a = temp[begin];temp[begin] = temp[end];temp[end] = a;begin++;end--;}    str = String.valueOf(temp);//将char[]转成str 不是用tostring方法return str;}}


原创粉丝点击