简体   繁体   English

如何针对输入的大量字符串优化我的代码

[英]How can I optimize my code for large number of strings on input

I passed 4 tests on my university compiler and the problem is the 5th one.我在大学编译器上通过了 4 次测试,问题是第 5 次。 Time limit is 1second for each test.每个测试的时间限制为 1 秒。 How can I optimize this code, maybe there is a better option for sorting if I compare strings?如何优化此代码,如果比较字符串,也许有更好的排序选项? My code:我的代码:

#include <iostream>
#include <string.h>

using namespace std;

void qsort(string &tab, int min, int max)
{
    if(min<max)
    {
        int min_min = min;
        for(int i=min+1;i<=max;i++)
        {
            if(tab[i]<tab[min])
            {
                swap(tab[++min_min],tab[i]);
            }
        }
        swap(tab[min],tab[min_min]);
        qsort(tab,min,min_min-1);
        qsort(tab,min_min+1,max);

    }
}
bool sprawdz(string tab,string tab2)
{
    for(int i=0;i<tab.length();i++)
    {
        if(tab[i]!=tab2[i])
        {
            return false;
            break;
        }
    }
    return true;
}

int main()
{
    string tablica1, tablica2;
    int ile;

    scanf("%d",&ile);
    for(int i=0;i<ile;i++)
    {
        cin>>tablica1>>tablica2;
        qsort(tablica1,0,tablica1.length()-1);
        qsort(tablica2,0,tablica2.length()-1);

        if(tablica1==tablica2)
        {
            printf("TAK\n");
        }
        else
        {
            printf("NIE\n");
        }


    }

    return 0;
}

Only information it thrown is min = 25177 max = 25978 so these numbers are quite large.它抛出的唯一信息是 min = 25177 max = 25978 所以这些数字相当大。 Any ideas?有任何想法吗? Task is to check if words are anagrams.任务是检查单词是否是字谜。

maybe there is a better option for sorting if I compare strings?如果我比较字符串,也许有更好的排序选择?

My favourite tip: The optimal way to do something is to not do it ;)我最喜欢的提示:做某事的最佳方式是不做;)

You do not have to sort the strings to check if they are anagrams.您不必对字符串进行排序以检查它们是否为字谜。 Order does not matter for anagrams, so why sort them?顺序对于字谜来说无关紧要,那么为什么要对它们进行排序呢?

Sorting is typically O(n log n) , while simply counting the frequency of characters is O(n) .排序通常是O(n log n) ,而简单地计算字符的频率是O(n) To count characters you can use a std::unordered_map , or if that is not allowed use an array of counters.要计算字符,您可以使用std::unordered_map ,或者如果不允许使用计数器数组。 Traverse the strings to count occurences of each character, then compare the arrays of counters.遍历字符串以计算每个字符的出现次数,然后比较计数器数组。

PS: You should also check if the size of the strings is the same before applying any further logic. PS:在应用任何进一步的逻辑之前,您还应该检查字符串的大小是否相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM