📌  相关文章
📜  给定两个字符串中常见的最长前缀字谜的长度

📅  最后修改于: 2021-09-06 06:10:20             🧑  作者: Mango

给定长度分别为NM 的两个字符串str1str2 ,任务是找到最长的变位字符串的长度,即两个字符串的前缀子串。

例子:

方法:思路是使用Hashing来解决上述问题。请按照以下步骤解决问题:

  • 初始化两个整数数组freq1[]freq2[] ,每个数组的大小为26 ,以分别存储字符串str1str2 中的字符数。
  • 初始化一个变量,比如ans ,以存储结果。
  • 迭代索引[0, minimum(N – 1, M – 1)] 中存在的字符串的字符并执行以下操作:
    • 递增计数STR1 [i]FREQ1 []数组,并通过1STR2计数[i]FREQ2 []数组。
    • 检查频率数组freq1[]与频率数组freq2 []是否相同赋值ans = i + 1
  • 经过以上步骤,打印ans的值作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
#define SIZE 26
 
// Function to check if two arrays
// are identical or not
bool longHelper(int freq1[], int freq2[])
{
    // Iterate over the range [0, SIZE]
    for (int i = 0; i < SIZE; ++i) {
 
        // If frequency any character is
        // not same in both the strings
        if (freq1[i] != freq2[i]) {
            return false;
        }
    }
 
    // Otherwise
    return true;
}
 
// Function to find the maximum
// length of the required string
int longCommomPrefixAnagram(
    string s1, string s2, int n1, int n2)
{
    // Store the count of
    // characters in string str1
    int freq1[26] = { 0 };
 
    // Store the count of
    // characters in string str2
    int freq2[26] = { 0 };
 
    // Stores the maximum length
    int ans = 0;
 
    // Minimum length of str1 and str2
    int mini_len = min(n1, n2);
 
    for (int i = 0; i < mini_len; ++i) {
 
        // Increment the count of
        // characters of str1[i] in
        // freq1[] by one
        freq1[s1[i] - 'a']++;
 
        // Increment the count of
        // characters of str2[i] in
        // freq2[] by one
        freq2[s2[i] - 'a']++;
 
        // Checks if prefixes are
        // anagram or not
        if (longHelper(freq1, freq2)) {
            ans = i + 1;
        }
    }
 
    // Finally print the ans
    cout << ans;
}
 
// Driver Code
int main()
{
    string str1 = "abaabcdezzwer";
    string str2 = "caaabbttyh";
    int N = str1.length();
    int M = str2.length();
 
    // Function Call
    longCommomPrefixAnagram(str1, str2,
                            N, M);
 
    return 0;
}


Java
// Java program for the above approach
public class Main
{
  static int SIZE = 26;
 
  // Function to check if two arrays
  // are identical or not
  static boolean longHelper(int[] freq1, int[] freq2)
  {
 
    // Iterate over the range [0, SIZE]
    for (int i = 0; i < SIZE; ++i)
    {
 
      // If frequency any character is
      // not same in both the strings
      if (freq1[i] != freq2[i])
      {
        return false;
      }
    }
 
    // Otherwise
    return true;
  }
 
  // Function to find the maximum
  // length of the required string
  static void longCommomPrefixAnagram(
    String s1, String s2, int n1, int n2)
  {
    // Store the count of
    // characters in string str1
    int[] freq1 = new int[26];
 
    // Store the count of
    // characters in string str2
    int[] freq2 = new int[26];
 
    // Stores the maximum length
    int ans = 0;
 
    // Minimum length of str1 and str2
    int mini_len = Math.min(n1, n2);
 
    for (int i = 0; i < mini_len; ++i) {
 
      // Increment the count of
      // characters of str1[i] in
      // freq1[] by one
      freq1[s1.charAt(i) - 'a']++;
 
      // Increment the count of
      // characters of str2[i] in
      // freq2[] by one
      freq2[s2.charAt(i) - 'a']++;
 
      // Checks if prefixes are
      // anagram or not
      if (longHelper(freq1, freq2)) {
        ans = i + 1;
      }
    }
 
    // Finally print the ans
    System.out.print(ans);
  }
 
  // Driver code
  public static void main(String[] args)
  {
    String str1 = "abaabcdezzwer";
    String str2 = "caaabbttyh";
    int N = str1.length();
    int M = str2.length();
 
    // Function Call
    longCommomPrefixAnagram(str1, str2, N, M);
  }
}
 
// This code is contributed by divyeshrrabadiya07.


Python3
# Python3 program for the above approach
SIZE = 26
 
# Function to check if two arrays
# are identical or not
def longHelper(freq1, freq2):
     
    # Iterate over the range [0, SIZE]
    for i in range(26):
 
        # If frequency any character is
        # not same in both the strings
        if (freq1[i] != freq2[i]):
            return False
 
    # Otherwise
    return True
 
# Function to find the maximum
# length of the required string
def longCommomPrefixAnagram(s1, s2, n1, n2):
   
    # Store the count of
    # characters in str1
    freq1 = [0]*26
 
    # Store the count of
    # characters in str2
    freq2 = [0]*26
 
    # Stores the maximum length
    ans = 0
 
    # Minimum length of str1 and str2
    mini_len = min(n1, n2)
    for i in range(mini_len):
 
        # Increment the count of
        # characters of str1[i] in
        # freq1[] by one
        freq1[ord(s1[i]) - ord('a')] += 1
 
        # Increment the count of
        # characters of stord(r2[i]) in
        # freq2[] by one
        freq2[ord(s2[i]) - ord('a')] += 1
 
        # Checks if prefixes are
        # anagram or not
        if (longHelper(freq1, freq2)):
            ans = i + 1
 
    # Finally prthe ans
    print (ans)
 
# Driver Code
if __name__ == '__main__':
    str1 = "abaabcdezzwer"
    str2 = "caaabbttyh"
    N = len(str1)
    M = len(str2)
 
    # Function Call
    longCommomPrefixAnagram(str1, str2, N, M)
     
    # This code is contributed by mohit kumar 29.


C#
// C# program for the above approach
using System;
class GFG
{   
    static int SIZE = 26;
     
    // Function to check if two arrays
    // are identical or not
    static bool longHelper(int[] freq1, int[] freq2)
    {
       
        // Iterate over the range [0, SIZE]
        for (int i = 0; i < SIZE; ++i)
        {
      
            // If frequency any character is
            // not same in both the strings
            if (freq1[i] != freq2[i])
            {
                return false;
            }
        }
      
        // Otherwise
        return true;
    }
     
    // Function to find the maximum
    // length of the required string
    static void longCommomPrefixAnagram(
        string s1, string s2, int n1, int n2)
    {
        // Store the count of
        // characters in string str1
        int[] freq1 = new int[26];
      
        // Store the count of
        // characters in string str2
        int[] freq2 = new int[26];
      
        // Stores the maximum length
        int ans = 0;
      
        // Minimum length of str1 and str2
        int mini_len = Math.Min(n1, n2);
      
        for (int i = 0; i < mini_len; ++i) {
      
            // Increment the count of
            // characters of str1[i] in
            // freq1[] by one
            freq1[s1[i] - 'a']++;
      
            // Increment the count of
            // characters of str2[i] in
            // freq2[] by one
            freq2[s2[i] - 'a']++;
      
            // Checks if prefixes are
            // anagram or not
            if (longHelper(freq1, freq2)) {
                ans = i + 1;
            }
        }
      
        // Finally print the ans
        Console.Write(ans);
    }
 
  // Driver code
  static void Main() {
    string str1 = "abaabcdezzwer";
    string str2 = "caaabbttyh";
    int N = str1.Length;
    int M = str2.Length;
  
    // Function Call
    longCommomPrefixAnagram(str1, str2, N, M);
  }
}
 
// This code is contributed by divyesh072019.


Javascript


输出:
6

时间复杂度: O(N*26)
辅助空间: O(26)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live