其他分享
首页 > 其他分享> > 力扣151. 翻转字符串里的单词

力扣151. 翻转字符串里的单词

作者:互联网

力扣链接:151. 翻转字符串里的单词
在这里插入图片描述

这一题我的解法里包含了多个子函数,可以说,这一题里面包含了好几个题目。这种解法思路清晰,容易理解,所以记录下来。

C语言版:

void swap(char* a, char* b)
{
    char tmp = *a;
    *a = *b;
    *b = tmp;
}
char* reverse(char* s, unsigned int start, unsigned int end)
{
    int i = start;
    int j = end;
    if (start >= end)
    {
        return s;
    }
    for (; i < j; i++, j--)
    {
        swap(&s[i], &s[j]);
    }
    return s;
}

char* removeExtraSpaces(char* s)
{
    int i = 1;
    int len = 0;
    int origin_len = strlen(s);
    if (s[0] != ' ')
    {
        s[len++] = s[0];
    }
    while (i < origin_len)
    {
        if (s[i] == ' ' && s[i - 1] == ' ')
        {
        }
        else
        {
            s[len++] = s[i];
        }
        i++;
    }
    if (s[len - 1] == ' ')
    {
        s[len - 1] = '\0';
    }
    else
    {
        s[len] = '\0';
    }
    return s;
}

char* reverseWords(char* s)
{
    int len;
    int left;
    int right;
    removeExtraSpaces(s);
    len = strlen(s);
    reverse(s, 0, len - 1);
    for (left = 0, right = 1; right <= len; right++)
    {
        if (s[right] == ' ' || right == len)
        {
            reverse(s, left, right - 1);
            left = right + 1;
        }
    }
    return s;
}

C++版:

class Solution {
public:
    string reverse(string& s, int start, int end)
    {
        if (start >= end)
        {
            return s;
        }
        for (int i = start, j = end; i < j; i++, j--)
        {
            swap(s[i], s[j]);
        }
        return s;
    }
    string removeExtraSpaces(string& s)
    {
        unsigned int i = 1;
        while (i < s.size())
        {
            if (s[i] == ' ' && s[i - 1] == ' ')
            {
                s.erase(s.begin() + i);
            }
            else
            {
                i++;
            }
        }
        if (s[0] == ' ')
        {
            s.erase(s.begin());
        }
        if (s[s.size() - 1] == ' ')
        {
            s.erase(s.end());
        }
 
        return s;
    }
    string reverseWords(string s) {
        removeExtraSpaces(s);
        reverse(s, 0, s.size() - 1);
        for (unsigned int left = 0, right = 1; right <= s.size(); right++)
        {
            if (s[right] == ' ' || right == s.size())
            {
                reverse (s, left, right - 1);
                left = right + 1;
            }
        }
        return s;
    }
};

标签:151,char,right,return,int,len,力扣,end,翻转
来源: https://blog.csdn.net/weixin_44175439/article/details/120705046