📌  相关文章
📜  查找给定字符串数组中具有位置的每个字符的频率

📅  最后修改于: 2022-05-13 01:56:05.054000             🧑  作者: Mango

查找给定字符串数组中具有位置的每个字符的频率

给定一个由N个字符串组成的数组arr[] ,其中字符串的每个字符都是小写英文字母,任务是存储和打印每个字符串中每个不同字符的出现次数。

例子:

方法:上述问题可以使用 Map 和 Vector 数据结构来解决。请按照以下步骤解决问题:

  • 初始化一个 map> > 说mp来存储一个字符在对向量中的出现,其中每对存储字符串在数组中的索引作为第一个元素和位置字符中的字符串作为第二个元素。
  • 使用变量i遍历向量arr并执行以下步骤:
    • 使用变量j迭代字符串arr[i]的字符,并在每次迭代中将对{i+1, j+1}推入向量mp[arr[i][j]]。
  • 最后,完成上述步骤后,通过遍历映射mp打印每个字符的出现。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to print every occurrence
// of every characters in every string
void printOccurrences(vector arr, int N)
{
    map > > mp;
 
    // Iterate over the vector arr[]
    for (int i = 0; i < N; i++) {
        // Traverse the string arr[i]
        for (int j = 0; j < arr[i].length(); j++) {
 
            // Push the pair of{i+1, j+1}
            // in mp[arr[i][j]]
            mp[arr[i][j]].push_back(
                make_pair(i + 1, j + 1));
        }
    }
    // Print the occurrences of every
    // character
    for (auto it : mp) {
        cout << "Occurrences of: " << it.first << " = ";
        for (int j = 0; j < (it.second).size(); j++) {
            cout << "[" << (it.second)[j].first << " "
                 << (it.second)[j].second << "] ";
        }
        cout << endl;
    }
}
 
// Driver Code
int main()
{
    // Input
    vector arr = { "geeksforgeeks", "gfg" };
    int N = arr.size();
    // Function call
    printOccurrences(arr, N);
}


Python3
# Python3 program for the above approach
 
# Function to print every occurrence
# of every characters in every string
def printOccurrences(arr, N):
     
    mp = [[] for i in range(26)]
 
    # Iterate over the vector arr[]
    for i in range(N):
         
        # Traverse the string arr[i]
        for j in range(len(arr[i])):
             
            # Push the pair of{i+1, j+1}
            # in mp[arr[i][j]]
            mp[ord(arr[i][j]) - ord('a')].append(
                           (i + 1, j + 1))
             
    # print(mp)
 
    # Print the occurrences of every
    # character
    for i in range(26):
        if len(mp[i]) == 0:
            continue
         
        print("Occurrences of:", chr(i +
              ord('a')), "=", end = " ")
        for j in mp[i]:
            print("[" + str(j[0]) + " " +
                        str(j[1]) + "] ", end = "")
        print()
 
# Driver Code
if __name__ == '__main__':
     
    # Input
    arr= [ "geeksforgeeks", "gfg" ]
    N  = len(arr)
     
    # Function call
    printOccurrences(arr, N)
 
# This code is contributed by mohit kumar 29


Javascript


输出
Occurrences of: e = [1 2] [1 3] [1 10] [1 11] 
Occurrences of: f = [1 6] [2 2] 
Occurrences of: g = [1 1] [1 9] [2 1] [2 3] 
Occurrences of: k = [1 4] [1 12] 
Occurrences of: o = [1 7] 
Occurrences of: r = [1 8] 
Occurrences of: s = [1 5] [1 13] 

时间复杂度: O(N*M),其中 M 是最长字符串的长度。
辅助空间: O(N*M)