【leetcode】翻转单词顺序

char* reverseWords(char* s){
    int len = strlen(s);
    int count = 0;       //单词数量 如果只有一个 头部不加空格
    int len_word = 0;  //单词长度包括标点符号
    char* str = (char*)malloc(len+1);
    char* p = str;
    for (int i=len-1; i>=0; i--)
    {
        if (s[i] != ' ')
            len_word++;
        if ((s[i]==' ') && len_word)
        {
            count++;
            if (count >1)
                *p++ = ' ';
            for (int j=i+1; j <= i + len_word; j++)
                *p++ = s[j];
            len_word = 0;
        }
        if (i ==0 && len_word) //字符串头部需要判断下
        {
            count++;
            if (count >1)
                *p++ = ' ';
            for (int j=i; j < i + len_word; j++)
                *p++ = s[j];
        }
    }
    *p = '\0';
    return str;
}
原文地址:https://www.cnblogs.com/ganxiang/p/13525307.html