Home > Software design >  reducing time complexity of compare two characters in one single string in c [closed]
reducing time complexity of compare two characters in one single string in c [closed]

Time:09-16

I have to compare first letter of a string with other letters of string in c for ex: in "bsadasdaddgkoj" i have to compare b i.e first letter to all other letters and see if it is alphabetically smaller but i have to do this really quick

vector<string> possibleChanges(vector<string> usernames) {
int n=usernames.size();
 vector<string> answers(n);
 for(int i=0;i<n;i  ) {
     for(int j=1;j<usernames[i].size();j  ) {
        if(usernames[i][0] > usernames[i][j]){
            answers[i] = "YES";
            break;
        }
    }
    if(answers[i]!="YES") answers[i]="NO";
 }
 return answers;
}

i have tried this so far this works but it is really slow.

CodePudding user response:

Let's assume that you really need answers as strings...

vector<string> possibleChanges(const vector<string>& usernames) {
 const size_t n = usernames.size();
 vector<string> answers(n, "NO");
 for (size_t i = 0; i < n;   i) {
    auto firstChar = usernames[i][0];
    auto it = std::find_if(usernames[i].begin()   1, usernames[i].end(), [&firstChar](std::string::value_type ch) { return firstChar > ch; });
    if (it != usernames[i].end())
       answers[i] = "YES";
 }
 return answers;
}

Also, if you know that usernames[i].size() >= 2 (or 4, or 8...), you could apply loop unrolling like:

for (size_t i = 0; i < n;   i) {
         auto firstChar = usernames[i][0];
         size_t j = 1;
         bool flag = false;
         for (; j   4 < usernames[i].size(); j  = 4) {
            if (firstChar > usernames[i][j] ||
               firstChar > usernames[i][j   1] ||
               firstChar > usernames[i][j   2] ||
               firstChar > usernames[i][j   3]) 
            {
               answers[i] = "YES";
               flag = true;
               break;
            }
               
         }
         for (; j < usernames[i].size() && !flag;   j) {
            if (firstChar > usernames[i][j]) {
               answers[i] = "YES";
               break;
            }
         }
  • Related