【问题标题】:Getting characters from the string vector从字符串向量中获取字符
【发布时间】:2020-12-08 12:07:10
【问题描述】:

我有一个字符串向量,并尝试使用两个循环来访问每个单词的每个字符,如下所示。有没有办法不使用两个循环,所以我不会超过 O(n) 时间复杂度。

澄清:我正在尝试将字母转换为电话键盘中的数字,然后搜索这些数字(如果它们在 phoneNumber 字符串中可用)。

  #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;
  }

【问题讨论】:

  • 不要超过 O(n) 是什么意思?使用多个嵌套循环并不总是意味着时间复杂度是非线性的,在您的情况下时间复杂度是 O(sum of words' length)
  • 我同意在最坏的情况下复杂度是 O(单词数 x 向量中最长的单词)。但我正试图以某种方式尽可能摆脱嵌套循环
  • 不要专注于大 O 符号。基于大 O 的误解相当普遍。您的代码具有复杂性 O(n) 来访问 n 字符。你不会变得更快
  • 为什么?嵌套循环没有任何问题。当然,您可以使用一些单一职责的方法并将内部循环放在单独的函数中。但总会有循环。
  • 你到底想在某些东西上做什么。

标签: c++ string vector mapping


【解决方案1】:

有没有办法不使用两个循环,所以我不会超过 O(n) 时间复杂度。

嵌套循环并不总是O(N^2)。或者更准确地说:big-O 仅在您说出 N 是什么时才有意义。这个循环很复杂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
     }
}

但是,您的循环非常类似于

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

N 是您要处理的字符数时,O( number_of_strings * number_of_characters ) 只不过是O(N)

另一种思考方式是考虑如果您对字符串"foobarcarcatlawyer" 执行相同的操作,复杂性会发生哪些变化。没有。如果你迭代这个字符串,你转换单个字符的次数保持不变。

您不能处理少于O(N)N 字符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-18
    • 2013-01-10
    相关资源
    最近更新 更多