📌  相关文章
📜  从给定的字符串中查找子字符串的最小起始索引,该字符串以连续的方式包含所有给定的单词

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

从给定的字符串中查找子字符串的最小起始索引,该字符串以连续的方式包含所有给定的单词

给定一个字符串S和一个相等长度的单词数组 (字符串) arr[]。任务是以连续的方式找到包含所有给定单词的子字符串的最小起始索引。如果没有找到这样的索引,则返回-1
注意:单词可以是任意顺序。

例子:

方法:可以通过找到最小索引处的任何单词来解决该任务,然后从第一个单词的结尾索引开始模拟该过程以检查所有其他单词是否存在于连续位置。
请按照以下步骤解决问题:

  • 将所有单词存储在无序集合中,例如st,以在恒定时间内查找单词。
  • 遍历字符串并检查从长度为M (每个单词的长度)的每个索引开始的子字符串,一旦找到有效的子字符串,即存在于S 中,则开始模拟前一个子字符串的结束索引之后的过程,并检查是否所有其他单词是否以连续的方式存在。
  • 如果以连续方式找到所有单词,则返回找到它的最小索引,否则返回 -1。

下面是上述方法的实现:

C++14
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find the min index
int minIndex(string arr[], string S, int N, int M)
{
    // Unordered set to store all words
    unordered_set st;
 
    // Insert each word in the set
    for (int i = 0; i < N; i++)
        st.insert(arr[i]);
 
    // Traverse over the string s
    for (int i = 0; i < S.size() - M; i++) {
        // Substring to check whether
        // it is part of array of
        // words or not
        string x = S.substr(i, M);
 
        // Variables to check the condition, store the
        // index and keep count of words
        int p = 0, k = -1, d = N;
 
        // If substring is one of the words
        if (st.find(x) != st.end()) {
 
            // Store the index
            k = i;
 
            // Decrement d
            d--;
 
            // Check further
            for (int j = i + M; j < S.size() - M; j += M) {
 
                // Substring to check
                // whether it is part of
                // array of words or not
                string y = S.substr(j, M);
 
                // If substring is not part of word
                if (d == 0)
                    break;
                if (st.find(y) == st.end()) {
                    p = 1;
                    i = j - 1;
                    break;
                }
                d--;
            }
        }
 
        // If index is found, return the index
        if (p == 0 and k != -1)
            return k;
    }
 
    // If no index found, return -1
    return -1;
}
 
// Driver Code
int main()
{
 
    // Input
    string arr[] = { "bat", "bal", "cat" };
    string S = "hellocatbyebalbatcatyo";
    int N = sizeof(arr) / sizeof(arr[0]);
    int M = arr[0].size();
 
    // Function call to find the minimum index
    cout << minIndex(arr, S, N, M);
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
class GFG{
 
// Function to find the min index
static int minIndex(String arr[], String S, int N, int M)
{
   
    // Unordered set to store all words
    HashSet st = new HashSet();
 
    // Insert each word in the set
    for (int i = 0; i < N; i++)
        st.add(arr[i]);
 
    // Traverse over the String s
    for (int i = 0; i < S.length() - M; i++)
    {
       
        // SubString to check whether
        // it is part of array of
        // words or not
        String x = S.substring(i, i+M);
 
        // Variables to check the condition, store the
        // index and keep count of words
        int p = 0, k = -1, d = N;
 
        // If subString is one of the words
        if (st.contains(x)) {
 
            // Store the index
            k = i;
 
            // Decrement d
            d--;
 
            // Check further
            for (int j = i + M; j < S.length() - M; j += M) {
 
                // SubString to check
                // whether it is part of
                // array of words or not
                String y = S.substring(j, j+M);
 
                // If subString is not part of word
                if (d == 0)
                    break;
                if (!st.contains(y)) {
                    p = 1;
                    i = j - 1;
                    break;
                }
                d--;
            }
        }
 
        // If index is found, return the index
        if (p == 0 && k != -1)
            return k;
    }
 
    // If no index found, return -1
    return -1;
}
 
// Driver Code
public static void main(String[] args)
{
 
    // Input
    String arr[] = { "bat", "bal", "cat" };
    String S = "hellocatbyebalbatcatyo";
    int N = arr.length;
    int M = arr[0].length();
    // Function call to find the minimum index
    System.out.print(minIndex(arr, S, N, M));
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python program for the above approach
 
# Function to find the min index
def minIndex(arr, S, N, M):
   
   # Unordered set to store all words
    st = set(arr)
     
    # Insert each word in the set
    for i in range(len(S)-M):
        x = S[i: i+M]
         
         # Variables to check the condition, store the
        # index and keep count of words
        p = 0
        k = -1
        d = N
         
        # If substring is one of the words
        if x in st:
           
          # Store the index
            k = i
             
           # Decrement d
            d -= 1
             
            # Traverse over the string s
            for j in range(i+M, len(S)-M, M):
               
               # Substring to check
                # whether it is part of
                # array of words or not
                y = S[j: j+M]
                 
                # If substring is not part of word
                if d == 0:
                    break
                if y not in st:
                    p = 1
                    i = j-1
                    break
                d -= 1
                 
        # If index is found, return the index
        if p == 0 and k != -1:
            return k
           
    # If no index found return -1     
    return -1
 
# Driver code
arr = ["bat", "bal", "cat"]
S = "hellocatbyebalbatcatyo"
N = len(arr)
M = len(arr[0])
print(minIndex(arr, S, N, M))
 
# This code is contributed by parthmanchanda81


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find the min index
static int minIndex(string []arr, string S, int N, int M)
{
    // Unordered set to store all words
    HashSet st = new HashSet();
 
    // Insert each word in the set
    for (int i = 0; i < N; i++)
        st.Add(arr[i]);
 
    // Traverse over the string s
    for (int i = 0; i < S.Length - M; i++) {
        // Substring to check whether
        // it is part of array of
        // words or not
        string x = S.Substring(i, M);
 
        // Variables to check the condition, store the
        // index and keep count of words
        int p = 0, k = -1, d = N;
 
        // If substring is one of the words
        if (st.Contains(x)) {
 
            // Store the index
            k = i;
 
            // Decrement d
            d--;
 
            // Check further
            for (int j = i + M; j < S.Length - M; j += M) {
 
                // Substring to check
                // whether it is part of
                // array of words or not
                string y = S.Substring(j, M);
 
                // If substring is not part of word
                if (d == 0)
                    break;
                if (st.Contains(y)==false) {
                    p = 1;
                    i = j - 1;
                    break;
                }
                d--;
            }
        }
 
        // If index is found, return the index
        if (p == 0 && k != -1)
            return k;
    }
 
    // If no index found, return -1
    return -1;
}
 
// Driver Code
public static void Main()
{
 
    // Input
    string []arr = { "bat", "bal", "cat" };
    string S = "hellocatbyebalbatcatyo";
    int N = arr.Length;
    int M = arr[0].Length;
 
    // Function call to find the minimum index
    Console.Write(minIndex(arr, S, N, M));
}
}
 
// This code is contributed by SURENDRA_GANGWAR.


Javascript



输出:
11

时间复杂度:O(S*M), S是字符串的长度, M是每个单词的长度
辅助空格:O(N),N是单词数