Reverse Words in a String

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

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

Clarification:

 

    • What constitutes a word?
      A sequence of non-space characters constitutes a word.
    • Could the input string contain leading or trailing spaces?
      Yes. However, your reversed string should not contain leading or trailing spaces.
    • How about multiple spaces between two words?
      Reduce them to a single space in the reversed string.

思路:确定好每一个字符串,然后加入到ArrayList中,字符串由前后空格分隔

java代码:

  1. public String reverseWords(String s) {
  2. ArrayList<String> res = new ArrayList<String>();
  3. int slen = s.length();
  4. int index = 0;
  5. while(true) {
  6. while(index<slen&&s.charAt(index)==' ') index++;
  7. if(index>=slen) break;
  8. int start = index;
  9. while(index<slen && s.charAt(index)!=' ') index++;
  10. int end = index;
  11. String str = s.substring(start,end);
  12. res.add(str);
  13. }
  14. StringBuffer strBuffer = new StringBuffer();
  15. if(res.size()==0) return "";
  16. strBuffer.append(res.get(res.size()-1));
  17. for(int i=res.size()-2;i>=0;i--) {
  18. strBuffer.append(" ");
  19. strBuffer.append(res.get(i));
  20. }
  21. return strBuffer.toString();
  22. }
posted @ 2014-07-27 12:47  purejade  阅读(89)  评论(0)    收藏  举报