【问题标题】:How do I efficiently find the number of substrings in a string with same first and last characters?如何有效地查找具有相同首尾字符的字符串中的子字符串数量?
【发布时间】:2015-06-20 18:38:27
【问题描述】:

我正在尝试查找字符串中第一个和最后一个字符相同的子字符串的数量。

我可以通过两个 for 循环以天真的方式解决它。

我觉得可以解决得更有效率。

如何以更有效的方式解决它?

【问题讨论】:

    标签: c++ string substring


    【解决方案1】:

    循环遍历字符串,并计算每个不同字符的出现次数。那么,如果一个字符只出现一次,则没有以它结尾和开始的子字符串,如果它出现两次——只有1次,如果3次——有3次,如果4次——6.函数是C( n,2) = n!/(2!(n-2)!) = n(n-1)/2.

    这是一个潜在的实现。

    inline int Nchoose2(int n) {
      return n*(n-1)/2;
    }
    
    std::string s;
    std::map<char,int> m;
    int cnt = 0;
    
    for (char c : s) {
      if (!m.count(c)) m[c] = 0;
      else ++m[c];
    }
    
    for (auto &c : m)
       cnt += Nchoose2(c.second);
    

    【讨论】:

      猜你喜欢
      • 2023-03-10
      • 2015-05-16
      • 2019-02-17
      • 2012-10-24
      • 2017-01-14
      • 2014-10-31
      • 2019-07-16
      • 2015-09-08
      • 1970-01-01
      相关资源
      最近更新 更多