LeetCode151. Multiple solutions to flip words in a string

LeetCode151. Flip the words in the string

topic

Medium difficulty

Given a string, flip each word in the string one by 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"
解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。

Description:

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

Solution: Python Dafa

  Seeing the requirements of this topic, the first idea is Python. Isn't this solved by one sentence? Just one sentence, one more sentence is not needed return " ".join(reversed(s.split())), just split him directly, and then reverse, then connect, all in one go, without any bells and whistles!

The entire code is:

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        return " ".join(reversed(s.split()))

Solution two: manually realize the function function

  If you manually implement this function, we can first reverse the entire character, and then match from the first non-empty character until the empty character, which is a word, and then reverse the word, That's it! In this loop, we traverse the entire string to complete the conversion, the code is as follows:

class Solution {
public:
    string reverseWords(string s) {
        // 反转整个字符串
        reverse(s.begin(), s.end());
        int n = s.size();
        int idx = 0;
        for (int i = 0; i < n; ++i) {
          	// 如果当前不为空,则开始为单词
            if (s[i] != ' ') {
                // 填一个空白字符然后将idx移动到下一个单词的开头位置
                if (idx != 0) s[idx++] = ' ';
                // 循环遍历至单词的末尾
                int end = i;
                while (end < n && s[end] != ' ') s[idx++] = s[end++];
                // 反转整个单词
                reverse(s.begin() + idx - (end - i), s.begin() + idx);
                // 更新i的值,寻找下一个单词
                i = end;
            }
        }
        s.erase(s.begin() + idx, s.end());
        return s;
    }
};
Published 180 original articles · praised 1217 · 120,000 views

Guess you like

Origin blog.csdn.net/qq_43422111/article/details/105443962