【发布时间】:2022-01-20 06:26:01
【问题描述】:
我不确定我的代码有什么问题。当我更改字符串单词时,它似乎大多数时候都打印 0 。希望有任何帮助/cmets - 我的代码中的逻辑有问题吗?如果是这样,在哪里以及如何纠正?
#include <stdio.h>
#include <cs50.h>
#include <string.h>
int check_unique_letters(string words);
int main (void)
{
string word = "ABCB" ;
printf ("%i\n", check_unique_letters (word));
}
int check_unique_letters (string words)
{
int j = 0;
do
{ int x = (int) (words [j]) ;
int y = 0;
for (int i=j + 1; i<strlen(words); i++)
{
if ((int)words[i] == x)
{
y += 1;
}
else
{
y+= 0;
}
}
if (y>0)
{
return 1;
break;
}
else
{
j = j+1;
}
}
while (j < strlen (words));
}
【问题讨论】:
-
如果外部
do .. while循环结束,那么你返回什么? -
不要在条件测试中使用
strlen- 在这种情况下,它会将名义上的 O(n^2) 算法转换为 O(n^4)。获取一次长度并将其存储在变量中 -
@Alnitak 您的建议通常是合理的,但是在这里获取长度一次并将其存储在变量中会将应该是 O(1) 算法的算法转换为 O(n)。更好的方法是将
strnlen(words, UCHAR_MAX+1)存储在一个变量中(可能自己编写strnlen 的等价物,因为它不是标准C)。任何长于 UCHAR_MAX 的字符串都会在前 UCHAR_MAX+1 个字符中有重复。 -
@PaulHankin
words是输入字符串,而不是找到与未找到标志的数组。如果没有这样的数组,算法总是 O(n^2) -
@Alnitak 这是此代码的 O(1) 版本:gist.github.com/paulhankin/363629b0eb731db3b60a1a40deaebfd2。使用
strlen而不是strnlen的相同代码是 O(n)。
标签: c char unique cs50 c-strings