📌  相关文章
📜  给定字符串在数组中出现的次数[l,r]

📅  最后修改于: 2021-04-29 11:17:13             🧑  作者: Mango

给定一个字符串数组arr []以及两个整数lr ,任务是查找给定字符串str在数组[l,r] (基于1的索引)中出现的次数。请注意,字符串仅包含小写字母。

例子:

方法:想法是使用unordered_map存储数组的第i个字符串所在的索引。如果给定字符串不存在于映射中,则答案为零,否则对映射中存在的给定字符串的索引执行二进制搜索,并找到在[L,R]范围内的字符串出现次数。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function to return the number of occurrences of
int NumOccurrences(string arr[], int n, string str, int L, int R)
{
    // To store the indices of strings in the array
    unordered_map > M;
    for (int i = 0; i < n; i++) {
        string temp = arr[i];
        auto it = M.find(temp);
  
        // If current string doesn't
        // have an entry in the map
        // then create the entry
        if (it == M.end()) {
            vector A;
            A.push_back(i + 1);
            M.insert(make_pair(temp, A));
        }
        else {
            it->second.push_back(i + 1);
        }
    }
  
    auto it = M.find(str);
  
    // If the given string is not
    // present in the array
    if (it == M.end())
        return 0;
  
    // If the given string is present
    // in the array
    vector A = it->second;
    int y = upper_bound(A.begin(), A.end(), R) - A.begin();
    int x = upper_bound(A.begin(), A.end(), L - 1) - A.begin();
  
    return (y - x);
}
  
// Driver code
int main()
{
    string arr[] = { "abc", "abcabc", "abc" };
    int n = sizeof(arr) / sizeof(string);
    int L = 1;
    int R = 3;
    string str = "abc";
  
    cout << NumOccurrences(arr, n, str, L, R);
  
    return 0;
}


Python3
# Python implementation of the approach
from bisect import bisect_right as upper_bound
from collections import defaultdict
  
# Function to return the number of occurrences of
def numOccurences(arr: list, n: int, string: str, L: int, R: int) -> int:
  
    # To store the indices of strings in the array
    M = defaultdict(lambda: list)
    for i in range(n):
        temp = arr[i]
  
        # If current string doesn't
        # have an entry in the map
        # then create the entry
        if temp not in M:
            A = []
            A.append(i + 1)
            M[temp] = A
        else:
            M[temp].append(i + 1)
  
    # If the given string is not
    # present in the array
    if string not in M:
        return 0
  
    # If the given string is present
    # in the array
    A = M[string]
    y = upper_bound(A, R)
    x = upper_bound(A, L - 1)
  
    return (y - x)
  
# Driver Code
if __name__ == "__main__":
    arr = ["abc", "abcabc", "abc"]
    n = len(arr)
    L = 1
    R = 3
    string = "abc"
  
    print(numOccurences(arr, n, string, L, R))
  
# This code is contributed by
# sanjeev2552


输出:
2