字符串中最长的单词
如何在不使用辅助字符串的情况下找到 const char 字符串中最长单词的长度?
#include <stdio.h>
int longest(const char *str) {
int max = 0, prev = 0, final_max = 0;
while (*str != '\0') {
prev = max;
max = 0;
while (1) {
if (*str != ' ')
max++;
str++;
if (*str == ' ')
break;
}
if (prev > max)
final_max = prev;
str++;
}
return final_max;
}
void main() {
const char str[] = "Longest word in string";
printf("%d", longest(str));
}
这将打印 4
作为最长单词的长度。你能帮我解决这个问题吗?
How can I find length of longest word in const char string without using auxiliary string?
#include <stdio.h>
int longest(const char *str) {
int max = 0, prev = 0, final_max = 0;
while (*str != '\0') {
prev = max;
max = 0;
while (1) {
if (*str != ' ')
max++;
str++;
if (*str == ' ')
break;
}
if (prev > max)
final_max = prev;
str++;
}
return final_max;
}
void main() {
const char str[] = "Longest word in string";
printf("%d", longest(str));
}
This prints 4
as length of longest word. Could you help me fix this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你可以找到线性时间内最长的单词。这肯定是最佳的,因为任何算法都必须至少处理每个字符一次。
基本思想是循环遍历字符串的每个字符,跟踪最后一个空格(或任何其他单词分隔符)的位置。每当当前字符是空格时,我们都会更新答案。
请注意,我们需要在末尾添加额外的检查,以防止最长的单词是字符串中的最后一个(因此后面不一定有空格)。
这是一个简单的实现:
You can find the longest word in linear time. This is surely optimal since any algorithm has to process every character at least once.
The basic idea is to loop over every character of the string, keeping track of the position of the last space (or any other word separator). Everytime the current character is a space we update the answer.
Note that we need to add an extra check at the end for the case where the longest word is the last in the string (and thus is not necessarily followed by a space).
Here's a simple implementation:
只需走一次绳子即可。
走过空格后,记下单词的开头。浏览完一个单词后,记下它的长度并与当前最长的长度进行比较。执行此操作直到检测到空字符。
使用
size_t
而不是int
来处理长字符串。通过
unsigned char*
访问字符以正确使用isspace()
。示例:
测试
输出
Simply walk the string once.
After walking past white spaces, note the beginning of a word. After walking through a word, note its length and compare to the current longest length. Do this until a null character detected.
Use
size_t
, rather thanint
to handle long strings.Access the characters via an
unsigned char*
to properly useisspace()
.Example:
Tests
Output
我想出了两种密切相关的算法,一种只报告最长单词的长度,但不报告它所在的位置,另一种则两者兼而有之。簿记跟踪迄今为止找到的最长单词和当前单词 - 在第一种情况下,仅跟踪长度;第二个是长度和起点。
长度 — 无位置
输出:
长度和位置
输出:
I came up with two closely related algorithms, one that only reports the length of the longest word but not where it is located, and the other which does both. The bookkeeping tracks the longest word found so far and the current word — in the first case, just the length; in the second, both the length and the starting point.
Length — no position
Output:
Length and position
Output: