【发布时间】:2011-05-02 16:10:30
【问题描述】:
我很难找到我编写的这段代码的空间和时间复杂度,以查找字符串中的回文数。
/**
This program finds palindromes in a string.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int checkPalin(char *str, int len)
{
int result = 0, loop;
for ( loop = 0; loop < len/2; loop++)
{
if ( *(str+loop) == *(str+((len - 1) - loop)) )
result = 1;
else {
result = 0;
break;
}
}
return result;
}
int main()
{
char *string = "baaab4";
char *a, *palin;
int len = strlen(string), index = 0, fwd=0, count=0, LEN;
LEN = len;
while(fwd < (LEN-1))
{
a = string+fwd;
palin = (char*)malloc((len+1)*sizeof(char));
while(index<len)
{
sprintf(palin+index, "%c",*a);
index++;
a++;
if ( index > 1 ) {
*(palin+index) = '\0';
count+=checkPalin(palin, index);
}
}
free(palin);
index = 0;
fwd++;
len--;
}
printf("Palindromes: %d\n", count);
return 0;
}
我试了一下,这就是我的想法:
在 main 中,我们有两个 while 循环。外层贯穿整个长度为 1 的字符串。现在这是混乱之处,内部 while 循环首先运行整个长度,然后是 n-1,然后是 n-2,以此类推,以用于外部 while 循环的每次迭代。那么这是否意味着我们的时间复杂度将是O(n(n-1)) = O(n^2-n) = O(n^2)?
对于空间复杂度,我最初为字符串长度+1分配空间,然后为(length+1)-1、(length+1)-2等分配空间,那么我们如何从中找到空间复杂度?
对于 checkPalin 函数,它的 O(n/2).
我正在准备面试,想了解这个概念。
谢谢
【问题讨论】:
标签: algorithm time-complexity palindrome space-complexity