码迷,mamicode.com
首页 > 其他好文 > 详细

Reverse Words in a String

时间:2016-07-06 13:20:17      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

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.
分析:
先取出多余的white space, 然后再进行(A^TB^T)^T = BA的转换。
 1 public class Solution {
 2     /**
 3      * @param s : A string
 4      * @return : A string
 5      */
 6     public String reverseWords(String s) {
 7         if (s == null || s.length() <= 1) return s;
 8 
 9         int start = 0;
10         List<Character> list = new ArrayList<Character>();
11         s = s.trim();
12 
13         for (int i = 0; i < s.length(); i++) {
14             if (!(s.charAt(i) ==   && list.get(list.size() - 1) ==  )) {
15                 list.add(s.charAt(i));
16             }
17         }
18 
19         for (int i = 0; i < list.size(); i++) {
20             if (list.get(i) ==  ) {
21                 swap(list, start, i - 1);
22                 start = i + 1;
23             }
24         }
25 
26         swap(list, start, list.size() - 1);
27         swap(list, 0, list.size() - 1);
28 
29         StringBuilder sb = new StringBuilder();
30         for (int i = 0; i < list.size(); i++) {
31             sb.append(list.get(i));
32         }
33         return sb.toString();
34     }
35 
36     public void swap(List<Character> list, int i, int j) {
37         while (i < j) {
38             char temp = list.get(i);
39             list.set(i, list.get(j));
40             list.set(j, temp);
41             i++;
42             j--;
43         }
44     }
45 }

 

 

Reverse Words in a String

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5646446.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!