时间复杂性(由于Hackerrank超时2秒而终止)

时间:2017-04-30 08:18:28

标签: c

建议一些方法来减少以下代码的时间复杂性。

问题是:

This is question
This is sample input output
此代码工作正常,除了两种情况(由于时间限制2s而终止)

#include<stdio.h>
#include<string.h>
int main()
    {
        unsigned char str[1000000];
        unsigned long int l;
        int i,j,t,k,c=0;
        scanf("%d",&t);
        for(k=0;k<t;k++)
        {
            c=0;
            scanf("%lu",&l);
            scanf("%s",str);
            for(i=0;i<l-1;i++)
            {
                for(j=i+1;j<l;j++)
                    if(str[i]=='S' && str[j]=='A')
                        c++;
            }
            printf("%d\n",c);
        }
        return 0;
    }

1 个答案:

答案 0 :(得分:0)

我使用以下算法来解决: 遍历字符串: 一个变量计数,它将存储当前找到的A之前的S的数量和总数,即已找到的总子串。

int total=0,count=0;
for(int j=0; j < s.length(); ++j){ //s.length or till wherever you want to find
    if(s[j] == 'A') total+=count;
    else if(s[j]=='S')  count++;
}
相关问题