leetcode-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".

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

click to show clarification.

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.

题目解析:1、生成的单词里面没有空格!

     2、输入的String,包括头或尾空格?    是的,反转的时候不能包含这些空格

              3、两个单词之间的多个空格? 只保留一个空格分析:两种方法:

代码1:

String[] parts = s.trim().split("\\s+");//去除前后的空格+去除里面的空格,得到一个没有空格的字符串

String out = "";

if (parts.length > 0) {   //从后往前输出,加入字符串

for (int i = parts.length - 1; i > 0; i--)

{ out += parts[i] + " "; }

out += parts[0]; }

return out;

代码2:通过反转整个字符串,去除不符合题目的空格;

再反转每一个单词;

package leetcode;

public class ReverseWordsinaString {  
           // reverses the part of an array and returns the input array for convenience
    public static char[] reverse(char[] arr, int i, int j) {
        while (i < j) {
            char tmp = arr[i];
            arr[i++] = arr[j];
            arr[j--] = tmp;
        }
        return arr;
    }
    public static String reverseWords(String s) {
        // reverse the whole string and convert to char array
        char[] str = reverse(s.toCharArray(), 0, s.length()-1);
     //  System.out.println(str.toString());
        int start = 0, end = 0; // start and end positions of a current word
        for (int i = 0; i < str.length; i++) {
            if (str[i] != ' ') { // if the current char is letter
                str[end++] = str[i]; // just move this letter to the next free pos
            } else if (i > 0 && str[i-1] != ' ') { // if the first space after word
                reverse(str, start, end-1); // reverse the word
                str[end++] = ' '; // and put the space after it
                start = end; // move start position further for the next word
            }
        }
       // System.out.println(s);
      // System.out.println(s.length());
        reverse(str, start, end-1);
        //为什么要加上面那一步呢???貌似没有区别
        
        // reverse the tail word if it's there
        // here's an ugly return just because we need to return Java's String
        // also as there could be spaces at the end of original string
        // we need to consider redundant space we have put there before
      //  System.out.println(s);
     //  System.out.println(s.length());

        return new String(str, 0, end > 0 && str[end-1] == ' ' ? end-1 : end);
    }  
    public static void main(String[] args) {
        System.out.println(reverseWords(" he ll o world!!      "));
        System.out.println(reverseWords(" he ll o world!!      ").length());
    }

}

 

posted @ 2016-04-29 11:38  wangb021  阅读(385)  评论(0编辑  收藏  举报