151. Reverse Words in a String I & Reverse Words in a String II

Reverse Words in a String I

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     public String reverseWords(String s) {
 3         if (s == null || s.length() < 1) return s;
 4         int i = 0;
 5         StringBuilder sb = new StringBuilder();
 6         while (i < s.length()) {
 7             StringBuilder temp = new StringBuilder();
 8             while(i < s.length() && !(s.charAt(i) == ' ')) {
 9                 temp.insert(0, s.charAt(i));
10                 i++;
11             }
12             if (temp.length() != 0) {
13                 sb.append(temp.toString());
14                 sb.append(' ');
15             }
16             while(i < s.length() && s.charAt(i) == ' ') {
17                 i++;
18             }
19         }
20         if (sb.length() > 0) {
21             sb.deleteCharAt(sb.length() - 1);
22         }
23         char[] arr = sb.toString().toCharArray();
24         reverse(arr);
25         
26         return new String(arr);
27     }
28 
29     public void reverse(char[] arr) {
30         int i = 0, j = arr.length - 1;
31         while (i < j) {
32             char temp = arr[i];
33             arr[i] = arr[j];
34             arr[j] = temp;
35             i++;
36             j--;
37         }
38     }
39 }

 Reverse Words in a String II

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

 Note: In the string, each word is separated by single space and there will not be any extra space in the string.

 1 public class Solution {
 2     public String reverseWords(String s) {
 3         char[] ca = s.toCharArray();
 4         int start = 0;
 5         for (int i = 0; i <= ca.length; i++) {
 6             if (i == ca.length || ca[i] == ' ') {
 7                 reverse(ca, start, i - 1);
 8                 start = i + 1;
 9             }
10         }
11         return new String(ca);
12     }
13 
14     private void reverse(char[] ca, int i, int j) {
15         for (; i < j; i++, j--) {
16             char tmp = ca[i];
17             ca[i] = ca[j];
18             ca[j] = tmp;
19         }
20     }
21 }

 

posted @ 2016-07-06 12:01  北叶青藤  阅读(178)  评论(0)    收藏  举报