C语言 | Leetcode C语言题解之第151题反转字符串中的单词

题目:

题解:

cpp 复制代码
void myResverse(char* s,int start,int end){
    while(start<end){
        char temp = s[start];
        s[start] = s[end];
        s[end] = temp;
        start++;
        end--;
    }
}
char* reverseWords(char* s) {
    int start = 0;
    int end = strlen(s)-1;
    myResverse(s,start,end);
    if(s[0]==' '){
        int i = 0;
        while(s[i]==' '){
            i++;
        }
        int j = 0;
        while(s[i]!='\0'){
            s[j] = s[i];
            i++;
            j++;
        }
        s[j] = '\0';
    }
    int check = 0;
    while(s[check]!='\0'){
        check++;
    }
    if(s[check-1]==' '){
        int o = check - 1;
        while(s[o]==' '){
            o--;
        }
        s[o+1] = '\0';
    }
    for(int k = 0;k<strlen(s);k++){
        if(s[k]==' '&&s[k+1]==' '){
            int i = k;
        while(s[i]==' '){
            i++;
        }
        int j = k+1;
        while(s[i]!='\0'){
            s[j] = s[i];
            i++;
            j++;
        }
        s[j] = '\0';
        }
    }
    int slow = 0;
    for(int u = 0;u<=strlen(s);u++){
        if(s[u]==' '||s[u]=='\0'){
            myResverse(s,slow,u-1);
            slow = u+1;
        }
    }
    return s;
}
相关推荐
khalil10201 天前
代码随想录算法训练营Day-46 动态规划13 | 647. 回文子串、516.最长回文子序列、动态规划总结
数据结构·c++·算法·leetcode·动态规划·回文子串·回文子序列
he___H1 天前
算法快与慢--哈希+双指针
算法·leetcode·哈希算法
凯瑟琳.奥古斯特1 天前
力扣2760 C++滑动窗口解法
数据结构·c++·算法·leetcode·职场和发展
_深海凉_1 天前
LeetCode热题100-不同路径
算法·leetcode·职场和发展
Byte Wizard1 天前
C语言指针深入浅出3
c语言·开发语言
m0_629494731 天前
LeetCode 热题 100-----23.反转链表
数据结构·算法·leetcode·链表
handler011 天前
速通蓝桥杯省一:二分算法
c语言·开发语言·c++·笔记·算法·职场和发展·蓝桥杯
爱编码的小八嘎1 天前
C语言完美演绎9-27
c语言
武帝为此1 天前
【C语言进程与线程】
c语言·开发语言
Byte Wizard1 天前
C语言指针深入浅出4
c语言·开发语言