📌  相关文章
📜  数组中前缀的最大出现次数

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

数组中前缀的最大出现次数

给定一个由小写英文字母组成的字符串。任务是计算字符串中出现次数最多的非空前缀作为子字符串的出现次数。
例子:

Input : str = "abbcdabbcd"
Output :  2
The prefix "abb" has maximum number of 
occurrences 2.

Input : str = "abc"
Output :  1

方法:这个想法是观察数组的每个前缀都必须包含字符串的第一个字符,并且它的每个相应的出现也将包含。此外,字符串字符最小长度前缀。因此,出现次数最多的前缀将是字符串本身的第一个字符。因此,现在任务减少到查找给定字符串中第一个字符的频率。
下面是上述方法的实现:

C++
// CPP program to find the number of occurrences
// of prefix which occurs maximum no. of time
 
#include 
using namespace std;
 
// Function to return the count of the
// required prefix
int prefixOccurrences(string str)
{
    char c = str[0];
    int countc = 0;
 
    // Find the frequency of first
    // character of string
    for (int i = 0; i < str.length(); i++) {
        if (str[i] == c)
            countc++;
    }
 
    return countc;
}
 
// Driver code
int main()
{
    string str = "abbcdabbcd";
    cout << prefixOccurrences(str);
 
    return 0;
}


Java
// Java program to find the number
// of occurrences of prefix which
// occurs maximum no. of time
class GFG
{
     
// Function to return the count of the
// required prefix
static int prefixOccurrences(String str)
{
    char c = str.charAt(0);
    int countc = 0;
 
    // Find the frequency of first
    // character of string
    for (int i = 0; i < str.length(); i++)
    {
        if (str.charAt(i) == c)
            countc++;
    }
 
    return countc;
}
 
// Driver code
public static void main(String args[])
{
    String str = "abbcdabbcd";
    System.out.println(prefixOccurrences(str));
 
}
}
 
// This code is contributed by Arnab Kundu


Python3
# Python3 program to find the number
# of occurrences of prefix which
# occurs maximum no. of time
 
# Function to return the count
# of the required prefix
def prefixOccurrences(str1):
 
    c = str1[0]
    countc = 0
 
    # Find the frequency of first
    # character of string
    for i in range(len(str1)):
        if (str1[i] == c):
            countc += 1
 
    return countc
 
# Driver code
str1 = "abbcdabbcd"
print(prefixOccurrences(str1))
 
# This code is contributed
# by mohit kumar


C#
// C# program to find the number
// of occurrences of prefix which
// occurs maximum no. of time
using System;
 
class GFG
{
     
    // Function to return the count of the
    // required prefix
    static int prefixOccurrences(string str)
    {
        char c = str[0];
        int countc = 0;
     
        // Find the frequency of first
        // character of string
        for (int i = 0; i < str.Length; i++)
        {
            if (str[i] == c)
                countc++;
        }
     
        return countc;
    }
     
    // Driver code
    public static void Main()
    {
        string str = "abbcdabbcd";
         
        Console.WriteLine(prefixOccurrences(str));
    }
}
 
// This code is contributed by Ryuga


Javascript


输出:

2