Imprime todas las strings en la array dada que ocurren como la substring en la string dada

Dada una array de strings arr[] y una string str , la tarea es imprimir todas las strings en arr[] que aparecen como una substring en str .

Ejemplo:

Entrada: str =”geeksforgeeks”, arr[] ={ “forg”, “geek”, “ek”, “dog”, “sfor”}
Salida: 
forg
geek
ek
sfor
Explicación: Las strings “forg”, “geek” , «ek» y «sfor» aparecen como una substring en str. Por lo tanto, el conteo requerido es 4.

Entrada: str =”abcd”, arr[] ={ “aa”, “bb”, “cc”}
Salida:  -1

 

Enfoque: El problema dado es un problema base de implementación. Se puede resolver iterando sobre la array de strings dada y para cada string en arr[] , verifique si ocurre como una substring de str o no usando el algoritmo discutido en este artículo. Mantenga una variable que almacene If no existe una string como una substring. En ese caso, imprima -1.

A continuación se muestra la implementación del enfoque anterior:

C++

// C++ program of the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Returns true if s1 is substring of s2
int isSubstring(string s1, string s2)
{
  int M = s1.length();
  int N = s2.length();
 
  /* A loop to slide pat[] one by one */
  for (int i = 0; i <= N - M; i++) {
    int j;
 
    /* For current index i, check for
        pattern match */
    for (j = 0; j < M; j++)
      if (s2[i + j] != s1[j])
        break;
 
    if (j == M)
      return i;
  }
 
  return -1;
}
 
// Function to print all the strings
// in the given array that occur as
// the substring in the given string
void isSubstr(string Str, string arr[], int len)
{
 
  // Stores if no string is a
  // substring of str
  int flag = 0;
 
  // Iterate over the array of strings
  for (int i = 0; i < len; i++)
  {
 
    // if the current string occur
    // as a substring in Str
    int s = isSubstring(arr[i],Str);
    if (s != -1) {
 
      // Print string i
      cout << arr[i] <<endl;
      flag = 1;
    }
  }
 
  // If no substring exist
  if (flag == 0)
    cout<<"-1"<<endl;
}
 
// Driver Code
int main()
{
  string arr[5]
    = { "forg", "geek", "ek", "dog", "sfo"};
  int len = sizeof(arr)/sizeof(arr[0]);
  string Str = "geeksforgeeks";
 
  isSubstr(Str, arr, len);
 
  return 0;
}
 
// This code is contributed by sanjoy_62.

Java

// JAVA program of the above approach
import java.util.*;
class GFG
{
   
    // Function to print all the strings
    // in the given array that occur as
    // the substring in the given string
    public static void isSubstr(String Str,
                                ArrayList<String> arr)
    {
       
        // Stores if no string is a
        // substring of str
        int flag = 0;
 
        // Iterate over the array of strings
        for (int i = 0; i < arr.size(); i++)
        {
           
            // if the current string occur
            // as a substring in Str
            if (Str.indexOf(arr.get(i)) != -1) {
 
                // Print string i
                System.out.println(arr.get(i));
                flag = 1;
            }
        }
       
        // If no substring exist
        if (flag == 0)
            System.out.print(-1);
    }
   
    // Driver Code
    public static void main(String[] args)
    {
        ArrayList<String> arr
            = new ArrayList<>(Arrays.asList(
                "forg", "geek", "ek", "dog", "sfo"));
        String Str = "geeksforgeeks";
 
        isSubstr(Str, arr);
    }
}
 
// This code is contributed by Taranpreet

Python3

# Python program of the above approach
 
# Function to print all the strings
# in the given array that occur as
# the substring in the given string
 
 
def isSubstr(Str, arr):
 
    # Stores if no string is a
    # substring of str
    flag = 0
 
    # Iterate over the array of strings
    for i in arr:
 
        # if the current string occur
        # as a substring in Str
        if i in Str:
 
            # Print string i
            print(i)
            flag = 1
 
    # If no substring exist
    if flag == 0:
        print(-1)
 
 
# Driver Code
arr = ["forg", "geek", "ek", "dog", "sfo"]
Str = "geeksforgeeks"
 
isSubstr(Str, arr)

C#

// C# program of the above approach
using System;
public class GFG
{
 
  // Function to print all the strings
  // in the given array that occur as
  // the substring in the given string
  public static void isSubstr(String Str,String[] arr)
  {
 
    // Stores if no string is a
    // substring of str
    int flag = 0;
 
    // Iterate over the array of strings
    for (int i = 0; i < arr.Length; i++)
    {
 
      // if the current string occur
      // as a substring in Str
      if (Str.IndexOf(arr[i]) != -1) {
 
        // Print string i
        Console.WriteLine(arr[i]);
        flag = 1;
      }
    }
 
    // If no substring exist
    if (flag == 0)
      Console.Write(-1);
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    String[] arr = {"forg", "geek", "ek", "dog", "sfo"};
    String Str = "geeksforgeeks";
 
    isSubstr(Str, arr);
  }
}
 
// This code is contributed by 29AjayKumar

Javascript

<script>
    // JavaScript program of the above approach
 
    // Function to print all the strings
    // in the given array that occur as
    // the substring in the given string
    const isSubstr = (Str, arr) => {
 
        // Stores if no string is a
        // substring of str
        let flag = 0;
 
        // Iterate over the array of strings
        for (i in arr)
        {
         
            // if the current string occur
            // as a substring in Str
            if (Str.indexOf(arr[i]) != -1)
            {
             
                // Print string i
                document.write(`${arr[i]}<br/>`);
                flag = 1;
            }
        }
         
        // If no substring exist
        if (flag == 0)
            document.write(-1);
 
    }
 
    // Driver Code
    let arr = ["forg", "geek", "ek", "dog", "sfo"];
    let Str = "geeksforgeeks";
 
    isSubstr(Str, arr)
 
    // This code is contributed by rakeshsahni
 
</script>
Producción

forg
geek
ek
sfo

Complejidad de Tiempo: O(N 2 )
Espacio Auxiliar: O(1)

Publicación traducida automáticamente

Artículo escrito por rexomkar y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *