104.Reverse Words in a String

来源:互联网 发布:olafur arnalds 知乎 编辑:程序博客网 时间:2024/05/29 19:23

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

click to show clarification.

Subscribe to see which companies asked this question

与剑指offer上的面试题42翻转单词序列类似,但是比那道题目多了限制条件。

并且要首先去掉str开头和结尾的空格,并且把字符串中间的多个空格用一个空格表示。这点与剑指offer上的不同。所以在开始的时候要把空格做处理。

/** * Given s = "the sky is blue", * return "blue is sky the".  * 并且要首先去掉str开头和结尾的空格,并且把字符串中间的多个空格用一个空格表示。这点与剑指offer上的不同。 * 所以在开始的时候要把空格做处理。 */ public String reverseWords(String str){ str = str.replaceAll("\\s{1,}", " "); if(str.length()<=0){ return ""; } if(str.charAt(0)==' '){str = str.substring(1);  } if(str.length()<=0){ return ""; } if(str.charAt(str.length()-1)==' '){ str = str.substring(0,str.length()-1); } return reverseWordsFromOffer(str); } public String reverseWordsFromOffer(String str) {        int len = str.length();        if(len <= 0){        return str;        }        /*首先反转整个句子*/        String s1 = Reverse(str,0,len-1);        /*逐个反转每个单词*/        for(int i=0;i<len;i++){        int low = i;        while(i<len && s1.charAt(i)!=' '){        i++;        }        int high = i-1;        if(low == high){/*长度为1的单词不需要反转*/        }else{        s1 = Reverse(s1,low,high);        }        }        return s1;    }    String Reverse(String s,int start ,int end){int len = s.length()-1;String s1 = s.substring(0,start);String s2 = s.substring(end+1);StringBuffer sb = new StringBuffer();for(int j=end;j>=start;j--){sb.append(s.charAt(j));}return s1 + new String(sb)+s2;}

细节决定成败,需要多多注意细节,认真考虑问题!!!!!!!!!!!!!!!!!!!!!

0 0