简体   繁体   中英

Getting characters from the string vector

I have a string vector and trying to reach each character of each word using two loops as shown below. Is there a way not using two loops so I don't go beyond O(n) time complexity.

clarification: What I'm trying to do is converting letters to numbers as in the phone key pad then searching those numbers if they're available in the phoneNumber string.

  #include<bits/stdc++.h> 
  using namespace std;

  // vector<string> words={"foo","bar","car","cat","lawyer"};
  // string phoneNumber="3226773664"

  void lookup(vector<string> &words,string phoneNumber){
  string strtonumber="";
  int ascii;

  for(auto word:words ){
    strtonumber="";
    for(auto chr:word ){
      ascii=int(chr);

      if(ascii >= 97 && ascii<=99)
      strtonumber+="2";
      if(ascii >= 100 && ascii<=102)
      strtonumber+="3";
      if(ascii >= 103 && ascii<=105)
      strtonumber+="4";
      if(ascii >= 106 && ascii<=108)
      strtonumber+="5";
      if(ascii >= 109 && ascii<=111)
      strtonumber+="6";
      if(ascii >= 112 && ascii<=115)
      strtonumber+="7";
      if(ascii >= 116 && ascii<=118)
      strtonumber+="8";
      if(ascii >= 119 && ascii<=122)
      strtonumber+="9";
  
    }
    
     if (phoneNumber.find(strtonumber) != string::npos)
        cout<<"Numerical version of these words available in your Phone Number string"<<endl;
  }

Is there a way not using two loops so I don't go beyond O(n) time complexity.

Nested loops are not always O(N^2) . Or more precisely: big-O is only meaningful when you say what N is. This loop is has complexity O(N^2) :

for (unsigned i=0; i < N; ++i) {
     for (unsigned j=0; j < N; ++j) {
          foo(i,j);                // <- this is called N*N times
     }
}

However, your loops are rather similar to

for (unsigned i=0; i < number_of_strings; ++i) {
     for (unsigned j=0; j < number_of_characters(i); ++j) {
          foo( words[i][j] );
     }
}

And O( number_of_strings * number_of_characters ) is nothing but O(N) when N is the number of characters you want to process.

Another way to think about it is to consider what changes about complexity if you would perform the same operations on a string "foobarcarcatlawyer" . Nothing. If you iterate this string the number of times you convert a single character stays exactly the same.

You cannot process N characters in less than O(N) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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