[LeetCode] 151. Reverse words in a string (same sword refers to Offer 58-I)

1. Topic

Given a string, flip each word in the string one by one.

Description:

  • No space characters form a word.
  • The input string can contain extra spaces before or after it, but the reversed characters cannot be included.
  • If there is an extra space between two words, reduce the space between the words after inversion to only one.

Example 1:

输入:"the sky is blue"
输出:"blue is sky the"

Example 2:

输入:"  hello world!  "
输出:"world! hello"
解释:输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。

Example 3:

输入:"a good   example"
输出:"example good a"
解释:如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。

Example 4:

输入:s = "  Bob    Loves  Alice   "
输出:"Alice Loves Bob"

Example 5:

输入:s = "Alice does not even like bob"
输出:"bob like even not does Alice"

prompt:

  • 1 <= s.length <= 104
  • s contains English uppercase and lowercase letters, numbers and spaces ''
  • At least one word in s

Advanced:

  • Please try the O(1) in-situ solution with additional space complexity.

Note: This question [Sword Finger Offer 58-I] has been changed from the original question

Two, solve

1. Library functions

Ideas:

The idea is simple, the steps are as follows:

  1. Remove leading and trailing spaces;
  2. Split the String with spaces and return a string array of words
  3. Reverse
  4. Connect back.

More specific: Omitted.

Code:

class Solution {
    
    
    public String reverseWords(String s) {
    
    
        String[] words = s.trim().split(" +");
        Collections.reverse(Arrays.asList(words));
        return String.join(" ", words);  // char[]连接成功,返回String格式
    }
}

Time complexity: O (n) O(n)O ( n ) , each function isO (n) O(n)O ( n ) .
Space complexity: O (n) O(n)O ( n )

2. Split + reverse order

Ideas:
1

Code:

class Solution {
    
    
    public String reverseWords(String s) {
    
    
    	// 1 && 2、删除首尾空格,分割字符串
        String[] strs = s.trim().split(" "); 
        StringBuilder res = new StringBuilder();
        // 3、倒序遍历,拼接至 StringBuilder
        for(int i = strs.length - 1; i >= 0; i--) {
    
     
            if(strs[i].equals("")) continue; // 遇到空单词则跳过
            res.append(strs[i] + " ");
        }
        // 4、转化为字符串,删除尾部空格,并返回
        return res.toString().trim(); 
    }
}

Time complexity: O (n) O(n)O ( n )
space complexity: O (n) O(n)O ( n )

3. Double pointer

Ideas:

Starting from the end, when a word is encountered, the ending position is recorded, and it is added to the StringBuilder until the first word.

Code:

class Solution {
    
    
    public String reverseWords(String s) {
    
    
        s = s.trim(); // 删除首尾空格
        int j = s.length() - 1, i = j;
        StringBuilder res = new StringBuilder();
        while(i >= 0) {
    
    
            while(i >= 0 && s.charAt(i) != ' ') i--; // 搜索首个空格
            res.append(s.substring(i + 1, j + 1) + " "); // 添加单词
            while(i >= 0 && s.charAt(i) == ' ') i--; // 跳过单词间空格
            j = i; // j 指向下个单词的尾字符
        }
        return res.toString().trim(); // 转化为字符串并返回
    }
}

Time complexity: O (n) O(n)O ( n )
space complexity: O (n) O(n)O ( n )

Three, reference

1. Reverse the word in the string
2. Interview Question 58-II. Rotate the string to the left (slice/list/string, clear illustration)
3. Java 3-line builtin solution
4. Clean Java two-pointers solution (no trim (), no split( ), no StringBuilder)
5. Java String join() with examples

Guess you like

Origin blog.csdn.net/HeavenDan/article/details/110951412