📌  相关文章
📜  形成给定字符串所需的字符串的前缀和后缀的最小数量

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

形成给定字符串所需的字符串的前缀和后缀的最小数量

给定两个字符串str1str2,任务是找到最小的前缀和后缀数 形成字符串str1 所需的str2 如果任务不可行,则返回“-1”。

例子:

方法:上述问题可以使用动态规划来解决。请按照以下步骤解决问题:

  • 初始化一个数组dp ,其中第 i 个元素arr[i]将存储形成一个字符串所需的最小连接,直到前缀索引i
  • dp[0] = 0dp数组的其他值初始化为-1
  • 初始化一个 HashSet
  • 从左到右迭代字符串str1并在每个索引处i
    • 将索引 0 到当前索引i的子字符串添加到 HashSet集中
  • 从右到左迭代字符串str1并在每个索引处i
    • 将索引i到结束索引的子字符串添加到 HashSet集中
  • 检查字符串str1中的所有子字符串并相应地更新dp
  • 最终答案将存储在dp[N] 中,其中N是字符串str1的长度

下面是上述方法的实现:

C++
// C++ implementation for the above approach
 
#include 
using namespace std;
 
// Function to find minimum number of
// concatenation of prefix and suffix
// of str2 to make str1
int partCount(string str1, string str2)
{
 
    // Initialize a set
    unordered_set set;
 
    // Initialize a temporary string
    string temp = "";
 
    int l1 = str1.length(), l2 = str2.length();
 
    // Iterate the string str2
    // from left to right
    for (int i = 0; i < l2; i++) {
 
        // Add current character
        // to string temp
        temp += str2[i];
 
        // Insert the prefix into hashset
        set.insert(temp);
    }
 
    // Re-initialize temp string
    // to empty string
    temp = "";
 
    // Iterate the string in reverse direction
    for (int i = l2 - 1; i >= 0; i--) {
 
        // Add current character to temp
        temp += str2[i];
 
        // Reverse the string temp
        reverse(temp.begin(), temp.end());
 
        // Insert the suffix into the hashset
        set.insert(temp);
 
        // Reverse the string temp again
        reverse(temp.begin(), temp.end());
    }
 
    // Initialize dp array to store the answer
    int dp[str1.length() + 1];
 
    memset(dp, -1, sizeof(dp));
    dp[0] = 0;
 
    // Check for all substrings starting
    // and ending at every indices
    for (int i = 0; i < l1; i++) {
        for (int j = 1; j <= l1 - i; j++) {
 
            // HashSet contains the substring
            if (set.count(str1.substr(i, j))) {
 
                if (dp[i] == -1) {
                    continue;
                }
                if (dp[i + j] == -1) {
                    dp[i + j] = dp[i] + 1;
                }
                else {
 
                    // Minimum of dp[i + j] and
                    // dp[i] + 1 will be stored
                    dp[i + j]
                        = min(dp[i + j], dp[i] + 1);
                }
            }
        }
    }
 
    // Return the answer
    return dp[str1.size()];
}
 
// Driver Code
int main()
{
    string str = "GEEKSFORGEEKS",
           wrd = "SFORGEEK";
 
    // Print the string
    cout << partCount(str, wrd);
}


Java
// Java implementation for the above approach
import java.util.Arrays;
import java.util.HashSet;
 
class GFG {
 
    // Function to find minimum number of
    // concatenation of prefix and suffix
    // of str2 to make str1
    public static int partCount(String str1, String str2) {
 
        // Initialize a set
        HashSet set = new HashSet();
 
        // Initialize a temporary string
        String temp = "";
 
        int l1 = str1.length(), l2 = str2.length();
 
        // Iterate the string str2
        // from left to right
        for (int i = 0; i < l2; i++) {
 
            // Add current character
            // to string temp
            temp += str2.charAt(i);
 
            // Insert the prefix into hashset
            set.add(temp);
        }
 
        // Re-initialize temp string
        // to empty string
        temp = "";
 
        // Iterate the string in reverse direction
        for (int i = l2 - 1; i >= 0; i--) {
 
            // Add current character to temp
            temp += str2.charAt(i);
 
            // Reverse the string temp
            temp = new StringBuffer(temp).reverse().toString();
 
            // Insert the suffix into the hashet
            set.add(temp);
 
            // Reverse the string temp again
            temp = new StringBuffer(temp).reverse().toString();
 
        }
 
        // Initialize dp array to store the answer
        int[] dp = new int[str1.length() + 1];
        Arrays.fill(dp, -1);
        dp[0] = 0;
 
        // Check for all substrings starting
        // and ending at every indices
        for (int i = 0; i < l1; i++) {
            for (int j = 1; j <= l1 - i; j++) {
 
                // HashSet contains the substring
                if (set.contains(str1.substring(i, i + j))) {
 
                    if (dp[i] == -1) {
                        continue;
                    }
                    if (dp[i + j] == -1) {
                        dp[i + j] = dp[i] + 1;
                    } else {
 
                        // Minimum of dp[i + j] and
                        // dp[i] + 1 will be stored
                        dp[i + j] = Math.min(dp[i + j], dp[i] + 1);
                    }
                }
            }
        }
 
        // Return the answer
        return dp[str1.length()];
    }
 
    // Driver Code
    public static void main(String args[]) {
        String str = "GEEKSFORGEEKS", wrd = "SFORGEEK";
 
        // Print the string
        System.out.println(partCount(str, wrd));
    }
}
 
// This code is contributed by gfgking.


Python3
# Python3 implementation for the above approach
 
# Function to find minimum number of
# concatenation of prefix and suffix
# of str2 to make str1
def partCount(str1, str2):
 
    # Initialize a set
    se = set()
 
    # Initialize a temporary string
    temp = ""
 
    l1 = len(str1)
    l2 = len(str2)
 
    # Iterate the string str2
    # from left to right
    for i in range(0, l2):
 
                # Add current character
                # to string temp
        temp += str2[i]
 
        # Insert the prefix into hashset
        se.add(temp)
 
        # Re-initialize temp string
        # to empty string
    temp = []
 
    # Iterate the string in reverse direction
    for i in range(l2 - 1, -1, -1):
 
                # Add current character to temp
        temp.append(str2[i])
 
        # Reverse the string temp
        temp.reverse()
 
        # Insert the suffix into the hashet
        se.add(''.join(temp))
 
        # Reverse the string temp again
        temp.reverse()
 
        # Initialize dp array to store the answer
    dp = [-1 for _ in range(len(str1) + 1)]
    dp[0] = 0
 
    # Check for all substrings starting
    # and ending at every indices
    for i in range(0, l1, 1):
        for j in range(1, l1 - i + 1):
 
                        # HashSet contains the substring
            if (str1[i:i+j] in se):
 
                if (dp[i] == -1):
                    continue
 
                if (dp[i + j] == -1):
                    dp[i + j] = dp[i] + 1
 
                else:
 
                    # Minimum of dp[i + j] and
                    # dp[i] + 1 will be stored
                    dp[i + j] = min(dp[i + j], dp[i] + 1)
 
        # Return the answer
    return dp[len(str1)]
 
# Driver Code
if __name__ == "__main__":
 
    str = "GEEKSFORGEEKS"
    wrd = "SFORGEEK"
 
    # Print the string
    print(partCount(str, wrd))
 
    # This code is contributed by rakeshsahni


C#
// C# implementation for the above approach
using System;
using System.Collections.Generic;
 
class GFG
{
    public static string Reverse(string Input)
    {
      
    // Converting string to character array
    char[] charArray = Input.ToCharArray();
      
    // Declaring an empty string
    string reversedString = String.Empty;
      
    // Iterating the each character from right to left
    for(int i = charArray.Length - 1; i > -1; i--)
    {
          
        // Append each character to the reversedstring.
        reversedString += charArray[i];
    }
      
    // Return the reversed string.
    return reversedString;
    }
 
    // Function to find minimum number of
    // concatenation of prefix and suffix
    // of str2 to make str1
    public static int partCount(string str1, string str2) {
 
        // Initialize a set
        HashSet set = new HashSet();
 
        // Initialize a temporary string
        string temp = "";
 
        int l1 = str1.Length, l2 = str2.Length;
 
        // Iterate the string str2
        // from left to right
        for (int i = 0; i < l2; i++) {
 
            // Add current character
            // to string temp
            temp += str2[i];
 
            // Insert the prefix into hashset
            set.Add(temp);
        }
 
        // Re-initialize temp string
        // to empty string
        temp = "";
 
        // Iterate the string in reverse direction
        for (int i = l2 - 1; i >= 0; i--) {
 
            // Add current character to temp
            temp += str2[i];
 
            // Reverse the string temp
            temp = Reverse(temp);
 
            // Insert the suffix into the hashet
            set.Add(temp);
 
            // Reverse the string temp again
            temp = Reverse(temp);
 
        }
 
        // Initialize dp array to store the answer
        int[] dp = new int[str1.Length + 1];
        for(int j=0; j


Javascript


输出
3

时间复杂度: O(N^3),其中 N 是 str1 的长度
辅助空间: O(N^2)