leetcode 151. Reverse Words in a String


Title Requirements

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.

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.

Speak a string of words in reverse order output, the word alphabetic order does not change. Among them, the first space in the string should be deleted. If there are redundant spaces in the string, only one space needs to be output.

Idea 1: regular expression

For more information about regular expressions, please refer to myThis blog
Here, we just need to read the words in the sentence through the regular expression of split. The regular expression used here is\s+That is to say, break a sentence when one or more blanks are encountered.

    public String reverseWords(String s) {
        String[] array = s.trim().split("\s+");
        String result = "";
        for(int i = array.length-1 ; i>0 ; i--){
            result += array[i] + " ";
        return result + array[0];

Idea 2: double pointer

In fact, the string API is also used for double pointer, but the core idea is to find the position of a word through double pointer, and then extract it and add it to the result set by obtaining the substring.

    public String reverseWords(String s){
        String trimmed = s.trim();
        int prev = trimmed.length();
        int index = prev;
        StringBuilder result = new StringBuilder();
        while ((index = trimmed.lastIndexOf(' ', index-1)) > 0) {
            if (index < prev-1) {
                result.append(trimmed.substring(index+1, prev));
                result.append(" ");
            prev = index;
        result.append(trimmed.substring(index+1, prev));
        return result.toString();

leetcode 151. Reverse Words in a String
For more development techniques, interview tutorials and Internet Co push, please welcome my WeChat official account. Benefits will be paid from time to time~