博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
小练习 - LeetCode151 Reverse Words in a String的C语言解法
阅读量:4208 次
发布时间:2019-05-26

本文共 2334 字,大约阅读时间需要 7 分钟。

很适合练习C语言基础,练习一个OJ题目除了找最佳解法,还可以多想想刻意去练习一些数据结构等其他知识点,举一反三。

Given an input string, reverse the string word by word.

Example:
Input: “the sky is blue”,
Output: “blue is sky the”.
Note:
A word is defined as a sequence of non-space characters.
Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
You need to reduce multiple spaces between two words to a single space in the reversed string.

解法一:练习字符串parse

size_t parse(const char *s, char *buf, size_t bufLen) {
size_t i = 0, j = 0, pos = bufLen - 1; while (s[i] == ' ' && s[i] != '\0') i++; j = i; while (s[i] != '\0') {
while (s[j] != ' ' && s[j] != '\0') j++; pos -= (j - i); memcpy(&buf[pos], &s[i], j - i); if (pos > 0) {
buf[--pos] = ' '; } while (s[j] == ' ' && s[j] != '\0') j++; i = j; } return buf[pos] == ' ' ? pos + 1: pos;}void reverseWords(char *s) {
size_t len = strlen(s) + 1; char *buf = malloc(len); memset(buf, 0, len); size_t pos = parse(s, buf, len); strcpy(s, &buf[pos]); free(buf);}

解法二:练习链表的使用

struct WordList {
char *word; struct WordList *next;};void insert(struct WordList **head, char *word) {
struct WordList *node = malloc(sizeof(struct WordList)); node->next = *head; node->word = word; *head = node;}void parse(const char *s, struct WordList **head) {
size_t i = 0, j = 0; while (s[i] == ' ' && s[i] != '\0') i++; j = i; while (s[i] != '\0') {
while (s[j] != ' ' && s[j] != '\0') j++; char *word = malloc(j - i + 1); memcpy(word, &s[i], j - i); word[j - i] = '\0'; insert(head, word); while (s[j] == ' ' && s[j] != '\0') j++; i = j; }}void reverseWords(char *s) {
struct WordList *head = NULL; parse(s, &head); struct WordList *cur = head, *tmp; s[0] = 0; while (cur) {
strcat(s, cur->word); if (cur->next) {
strcat(s, " "); } tmp = cur; cur = cur->next; free(tmp->word); free(tmp); }}

对比

上面两种方法parse字符串部分是一样的,区别在于存储,重点练习链表的解法调用了多次malloc和free,性能自然是比不过用一个array来操作的。结果也是:第一种array解法,runtime击败了100%的提交;第二种用链表只击败了2%。题目本身如果用C++或Java等都有标准库,直接就可以搞定,但是就失去了练习的目的了,用C语言用多种思路来解,就可以很好地起到练习的作用。

转载地址:http://rbqli.baihongyu.com/

你可能感兴趣的文章
如何给分类增加一个属性(后台)
查看>>
linux设置环境变量 临时设置 和 永久设置
查看>>
mysql数据库主从同步的问题解决方法
查看>>
LoadRunner如何在脚本运行时修改log设置选项?
查看>>
QC数据库表结构
查看>>
自动化测试工具的3个关键部分
查看>>
测试工具厂商的编程语言什么时候“退休”?
查看>>
资源监控工具 - Hyperic HQ
查看>>
LoadRunner中Concurrent与Simultaneous的区别
查看>>
SiteScope - Agentless监控
查看>>
QTP测试.NET控件CheckedListBox
查看>>
使用QTP的.NET插件扩展技术测试ComponentOne的ToolBar控件
查看>>
用上帝之眼进行自动化测试
查看>>
为LoadRunner写一个lr_save_float函数
查看>>
PrefTest工作室全新力作-《性能测试与调优实战》课程视频即将上线
查看>>
质量度量分析与测试技术 培训大纲
查看>>
欢迎加入【亿能测试快讯】邮件列表!
查看>>
为什么我们的自动化测试“要”这么难
查看>>
LoadRunner性能脚本开发实战训练
查看>>
测试之途,前途?钱途?图何?
查看>>