学习时间:
2023年3月6日
题目描述:
题解分享:
// 作 者 : 繁 华 倾 夏
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h> // 调用strlen函数
#include <stdlib.h> // 调用malloc函数
// 力扣(LeetCode):557. 反转字符串中的单词 III
// s:传入的字符串
char* reverseWords(char* s) {
int len = strlen(s); // 字符串的长度
char* re = (char*)malloc(sizeof(char) * (len + 1));// 申请空间
re[len] = 0; // 给数组尾部赋0,使之变为字符串
int i = 0; //
while (i < len) { // 遍历字符串
int start = i; //
while (i < len && s[i] != ' ') { // 不是空格则进行翻转判断
i++;
}
for (int p = start; p < i; p++) { // 翻转字符串
re[p] = s[start + i - 1 - p];
}
while (i < len && s[i] == ' ') { // 遇见空格则进位
re[i] = ' ';
i++;
}
}
return re; // 返回字符串
}
// 测试用例
// 输入 s = "Let's take LeetCode contest"
// 输出 "s'teL ekat edoCteeL tsetnoc"
int main() {
char s[] = "Let's take LeetCode contest";
char* re = reverseWords(s);
puts(re);
return 0;
}
【繁华倾夏】【每日力扣题解分享】【Day51】