“This is the 13th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021”

Subject analysis

Given a string, you need to reverse the character order of each word in the string, while still preserving the Spaces and the original order of the words.

  • Example 1:

Enter: “Let’s take LeetCode Contest”

“S ‘tel ekat edoCteeL tsetnoc”

  • In a string, each word is separated by a single space, and there are no extra Spaces in the string.

We only need to flip each word or phrase, and each word is separated by a space, so a simple idea is to divide the words by the space, and then flip each word. So we can have the following steps to complete:

  1. Split a string into an array with split;
  2. Iterate through the array, using reverse to flip each word;
  3. Splice the segmented string with SB1;
  4. Remove the last extra space when concatenation is complete.

Complexity analysis:

Time complexity: O(N), where N is the length of the string.

The code analysis

class Solution { public String reverseWords(String s) { StringBuffer sb1 = new StringBuffer(); String[] strArr = s.split(" "); for(String str : strArr){ StringBuilder sb2 = new StringBuilder(str); sb1.append(sb2.reverse().toString()).append(" "); } sb1.deleteCharAt(sb1.length() - 1); return sb1.toString(); }}Copy the code

Result: Yes

Execution time: 4 ms, beating 82.02% of all Java commits

Memory consumption: 38.9 MB, beating 74.55% of all Java commits

Here you can see the solution on the official website:

Open up a new string. It then iterates through the original string until it finds a space, at which point it finds a word and its starting and ending positions.

You can then put the word in reverse order into the new string, depending on where it starts and ends.

Do this multiple times until you have iterated through the original string, and you get the flipped result.

class Solution {
    public String reverseWords(String s) {
        StringBuffer ret = new StringBuffer();
        int length = s.length();
        int i = 0;
        while (i < length) {
            int start = i;
            while (i < length && s.charAt(i) != ' ') {
                i++;
            }
            for (int p = start; p < i; p++) {
                ret.append(s.charAt(start + i - 1 - p));
            }
            while (i < length && s.charAt(i) == ' ') {
                i++;
                ret.append(' ');
            }
        }
        return ret.toString();
    }
}
Copy the code

\