C++ 从字符串向量中获取字符

C++ 从字符串向量中获取字符,c++,string,vector,mapping,C++,String,Vector,Mapping,我有一个字符串向量,并尝试使用两个循环到达每个单词的每个字符,如下所示。有没有一种方法不使用两个循环,这样我就不会超过O(n)时间复杂度 澄清:我想做的是将字母转换成电话键盘上的数字,然后搜索那些在电话号码字符串中可用的数字 #include<bits/stdc++.h> using namespace std; // vector<string> words={"foo","bar","car"

我有一个字符串向量,并尝试使用两个循环到达每个单词的每个字符,如下所示。有没有一种方法不使用两个循环,这样我就不会超过O(n)时间复杂度

澄清:我想做的是将字母转换成电话键盘上的数字,然后搜索那些在电话号码字符串中可用的数字

  #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;
  }
#包括
使用名称空间std;
//向量词={“foo”、“bar”、“car”、“cat”、“lawyer”};
//字符串phoneNumber=“3226773664”
无效查找(向量和单词、字符串phoneNumber){
字符串strotnumber=“”;
int-ascii;
for(自动字:字){
strotnumber=“”;
用于(自动chr:word){
ascii=int(chr);
如果(ascii>=97&&ascii=100&&ascii=103&&ascii=106&&ascii=109&&ascii=112&&ascii=116&&ascii=119&&ascii
有没有一种方法不使用两个循环,这样我就不会超过O(n)时间复杂度

嵌套循环并不总是
O(N^2)
。或者更准确地说:只有当您说出
N
是什么时,big-O才有意义。此循环具有复杂性
O(N^2)

for(无符号i=0;ifoo(i,j);//你说不超过O(n)是什么意思?使用多个嵌套循环并不总是意味着时间复杂度是非线性的,在你的例子中,时间复杂度是
O(单词长度之和)
我同意在最坏的情况下复杂度是O(单词数x向量中最长的单词).但我正试图尽可能地摆脱嵌套循环。有些人并不专注于大O表示法。基于大O的误解相当普遍。您的代码具有复杂性
O(n)
访问
n
字符。不会太快。为什么?嵌套循环没有问题。当然,您可以使用某种单一责任方法,将内部循环放在一个单独的函数中。但始终会有循环。在某些东西中,您到底想做什么。
for (unsigned i=0; i < N; ++i) {
     for (unsigned j=0; j < N; ++j) {
          foo(i,j);                // <- this is called N*N times
     }
}
for (unsigned i=0; i < number_of_strings; ++i) {
     for (unsigned j=0; j < number_of_characters(i); ++j) {
          foo( words[i][j] );
     }
}