📌  相关文章
📜  包含另一个字符串作为子序列的给定字符串的最小子字符串的长度

📅  最后修改于: 2021-09-06 06:51:42             🧑  作者: Mango

给定两个字符串AB ,任务是找到A的最小子字符串,其中B作为子序列。

例子:

处理方法:按照以下步骤解决问题:

  • A中也存在于B中的所有字符索引存储在 Map CharacterIndex 中
  • 遍历字符串B 的所有字符。
  • 检查字符串B的第一个字符是否存在于字符串A 中
    1. 如果发现为真,则使用字符串A 中第一次出现B[0]的索引初始化两个变量firstVarlastVar
    2. 更新值后,从 Map CharacterIndex 中删除该字符。
    3. 否则,不可能有更多的子串。
  • 对于B的剩余字符,检查该字符是否存在于字符串A 中。如果发现是真的,遍历所有的字符串中的该字符的出现,如果该字符的字符串是一个指数超过lastVar,然后更新与该指数的lastVar。否则,不可能有更多的子串。
  • 如果B被完全遍历,用firstVarlastVar之间的差异更新答案
  • 打印最终最小化的答案。

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
#include 
using namespace std;
 
// Function to find the length of
// smallest substring of a having
// string b as a subsequence
int minLength(string a, string b)
{
 
    // Stores the characters present
    // in string b
    map Char;
    for (int i = 0; i < b.length(); i++) {
 
        Char[b[i]]++;
    }
 
    // Find index of characters of a
    // that are also present in string b
    map > CharacterIndex;
 
    for (int i = 0; i < a.length(); i++) {
 
        char x = a[i];
 
        // If character is present in string b
        if (Char.find(x) != Char.end()) {
 
            // Store the index of character
            CharacterIndex[x].push_back(i);
        }
    }
 
    int len = INT_MAX;
 
    // Flag is used to check if
    // substring is possible
    int flag;
 
    while (true) {
 
        // Assume that substring is
        // possible
        flag = 1;
 
        // Stores first and last
        // indices of the substring
        // respectively
        int firstVar, lastVar;
 
        for (int i = 0; i < b.length(); i++) {
 
            // For first character of string b
            if (i == 0) {
 
                // If the first character of
                // b is not present in a
                if (CharacterIndex.find(b[i])
                    == CharacterIndex.end()) {
 
                    flag = 0;
                    break;
                }
 
                // If the first character of b
                // is present in a
                else {
 
                    int x = *(
                        CharacterIndex[b[i]].begin());
 
                    // Remove the index from map
                    CharacterIndex[b[i]].erase(
                        CharacterIndex[b[i]].begin());
 
                    // Update indices of
                    // the substring
                    firstVar = x;
                    lastVar = x;
                }
            }
 
            // For the remaining characters of b
            else {
 
                int elementFound = 0;
                for (auto e : CharacterIndex[b[i]]) {
 
                    if (e > lastVar) {
 
                        // If index possible for
                        // current character
                        elementFound = 1;
                        lastVar = e;
                        break;
                    }
                }
                if (elementFound == 0) {
 
                    // If no index is possible
                    flag = 0;
                    break;
                }
            }
        }
 
        if (flag == 0) {
 
            // If no more substring
            // is possible
            break;
        }
 
        // Update the minimum length
        // of substring
        len = min(len,
                  abs(lastVar - firstVar) + 1);
    }
 
    // Return the result
    return len;
}
 
// Driver Code
int main()
{
 
    // Given two string
    string a = "abcdefababaef";
    string b = "abf";
 
    int len = minLength(a, b);
    if (len != INT_MAX) {
 
        cout << len << endl;
    }
    else {
 
        cout << "Impossible" << endl;
    }
}


Java
// Java program to implement
// the above approach
import java.util.ArrayList;
import java.util.HashMap;
 
class GFG{
 
// Function to find the length of
// smallest substring of a having
// string b as a subsequence
static int minLength(String a, String b)
{
     
    // Stores the characters present
    // in string b
    HashMap Char = new HashMap<>();
 
    for(int i = 0; i < b.length(); i++)
    {
        Char.put(b.charAt(i),
                 Char.getOrDefault(b.charAt(i), 0) + 1);
    }
 
    // Find index of characters of a
    // that are also present in string b
    HashMap>
        CharacterIndex = new HashMap<>();
 
    for(int i = 0; i < a.length(); i++)
    {
        char x = a.charAt(i);
 
        // If character is present in string b
        if (Char.containsKey(x))
        {
            if (CharacterIndex.get(x) == null)
            {
                CharacterIndex.put(
                    x, new ArrayList());
            }
             
            // Store the index of character
            CharacterIndex.get(x).add(i);
        }
    }
 
    int len = Integer.MAX_VALUE;
 
    // Flag is used to check if
    // substring is possible
    int flag;
 
    while (true)
    {
 
        // Assume that substring is
        // possible
        flag = 1;
 
        // Stores first and last
        // indices of the substring
        // respectively
        int firstVar = 0, lastVar = 0;
 
        for(int i = 0; i < b.length(); i++)
        {
             
            // For first character of string b
            if (i == 0)
            {
 
                // If the first character of
                // b is not present in a
                if (CharacterIndex.containsKey(i))
                {
                    flag = 0;
                    break;
                }
 
                // If the first character of b
                // is present in a
                else
                {
                    int x = CharacterIndex.get(b.charAt(i)).get(0);
 
                    // Remove the index from map
                    CharacterIndex.get(b.charAt(i)).remove(
                        CharacterIndex.get(b.charAt(i)).get(0));
 
                    // Update indices of
                    // the substring
                    firstVar = x;
                    lastVar = x;
                }
            }
 
            // For the remaining characters of b
            else
            {
                int elementFound = 0;
                for(var e :
                    CharacterIndex.get(b.charAt(i)))
                {
                    if (e > lastVar)
                    {
                         
                        // If index possible for
                        // current character
                        elementFound = 1;
                        lastVar = e;
                        break;
                    }
                }
                if (elementFound == 0)
                {
                     
                    // If no index is possible
                    flag = 0;
                    break;
                }
            }
        }
 
        if (flag == 0)
        {
 
            // If no more substring
            // is possible
            break;
        }
 
        // Update the minimum length
        // of substring
        len = Math.min(
            len, Math.abs(lastVar - firstVar) + 1);
    }
 
    // Return the result
    return len;
}
 
// Driver code
public static void main(String[] args)
{
     
    // Given two string
    String a = "abcdefababaef";
    String b = "abf";
 
    int len = minLength(a, b);
    if (len != Integer.MAX_VALUE)
    {
        System.out.println(len);
    }
    else
    {
        System.out.println("Impossible");
    }
}
}
 
// This code is contributed by sk944795


Python3
# Python3 program to implement
# the above approach
import sys
 
# Function to find the length of
# smallest substring of a having
# string b as a subsequence
def minLength(a, b):
     
    # Stores the characters present
    # in string b
    Char = {}
    for i in range(len(b)):
        Char[b[i]] = Char.get(b[i], 0) + 1
 
    # Find index of characters of a
    # that are also present in string b
    CharacterIndex = {}
 
    for i in range(len(a)):
        x = a[i]
 
        # If character is present in string b
        if (x in Char):
             
            # Store the index of character
            CharacterIndex[x] = CharacterIndex.get(x, [])
            CharacterIndex[x].append(i)
 
    l = sys.maxsize
 
    # Flag is used to check if
    # substring is possible
    while(True):
         
        # Assume that substring is
        # possible
        flag = 1
 
        firstVar = 0
        lastVar = 0
         
        # Stores first and last
        # indices of the substring
        # respectively
        for i in range(len(b)):
             
            # For first character of string b
            if (i == 0):
                 
                # If the first character of
                # b is not present in a
                if (b[i] not in CharacterIndex):
                    flag = 0
                    break
 
                # If the first character of b
                # is present in a
                else:
                    x = CharacterIndex[b[i]][0]
 
                    # Remove the index from map
                    CharacterIndex[b[i]].remove(
                    CharacterIndex[b[i]][0])
 
                    # Update indices of
                    # the substring
                    firstVar = x
                    lastVar = x
 
            # For the remaining characters of b
            else:
                elementFound = 0
                for e in CharacterIndex[b[i]]:
                    if (e > lastVar):
                         
                        # If index possible for
                        # current character
                        elementFound = 1
                        lastVar = e
                        break
                     
                if (elementFound == 0):
                     
                    # If no index is possible
                    flag = 0
                    break
                 
        if (flag == 0):
             
            # If no more substring
            # is possible
            break
 
        # Update the minimum length
        # of substring
        l = min(l, abs(lastVar - firstVar) + 1)
 
    # Return the result
    return l
 
# Driver Code
if __name__ == '__main__':
     
    # Given two string
    a = "abcdefababaef"
    b = "abf"
 
    l = minLength(a, b)
    if (l != sys.maxsize):
        print(l)
    else:
        print("Impossible")
         
# This code is contributed by SURENDRA_GANGWAR


输出:
5

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

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