Conteo mínimo de palabras entre todas las oraciones dadas

Dadas N oraciones en minúsculas, la tarea es encontrar el recuento mínimo de palabras entre todas estas oraciones. 

Ejemplos: 

Entrada: arr[] = { 
“hay una vaca”, 
“la vaca es nuestra madre”, 
“la vaca nos da leche y la leche es dulce”, 
“hay un niño que ama a la vaca”} 
Salida: 4
Explicación: Tanto la 1ra como la segunda oración tiene 4 palabras que es el mínimo posible.

Entrada: arr[] = { 
“abc aac abcd ccc”, 
“ac abc cca”, 
“abca aaac abcd ccc”} 
Salida:

 

Enfoque: Este es un problema basado en la implementación. La idea es encontrar el conteo de palabras en una oración para todas las oraciones dadas y mantener el conteo mínimo en una variable que es la respuesta requerida.

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

C++

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find count of
// words in the given string
int countword(string& a)
{
    // Stores word count
    int count = 1;
    for (int i = 0; i < a.size(); i++) {
 
        // If a new word is
        // encountered
        if (a[i] == ' ')
            count++;
    }
   
    // Return count
    return count;
}
 
// Function to find minimum count of
// words among all given sentences
int countleastWords(string arr[], int N)
{
    // Stores the final answer
    int ans = INT_MAX;
 
    // Loop to iterate over sentences
    for (int i = 0; i < N; i++) {
 
        // Stores count of words
        // in ith sentence
        int temp = countword(arr[i]);
 
        // Update answer
        if (temp < ans)
            ans = temp;
    }
 
    // Return Answer
    return ans;
}
// Driver code
int main()
{
    string arr[] = { "there is a cow",
                     "cow is our mother",
                     "cow gives us milk and \
                      milk is sweet",
                     "there is a boy who loves cow" };
    int N = 4;
 
    cout << countleastWords(arr, N) << endl;
    return 0;
}

Java

// Java code to implement above approach
import java.util.*;
public class GFG
{
 
  // Function to find count of
  // words in the given string
  static int countword(String a)
  {
 
    // Stores word count
    int count = 1;
    for (int i = 0; i < a.length(); i++) {
 
      // If a new word is
      // encountered
      if (a.charAt(i) == ' ')
        count++;
    }
 
    // Return count
    return count;
  }
 
  // Function to find minimum count of
  // words among all given sentences
  static int countleastWords(String[] arr, int N)
  {
 
    // Stores the final answer
    int ans = Integer.MAX_VALUE;
 
    // Loop to iterate over sentences
    for (int i = 0; i < N; i++) {
 
      // Stores count of words
      // in ith sentence
      int temp = countword(arr[i]);
 
      // Update answer
      if (temp < ans)
        ans = temp;
    }
 
    // Return Answer
    return ans;
  }
 
  // Driver code
  public static void main(String args[])
  {
    String[] arr
      = { "there is a cow", "cow is our mother",
         "cow gives us milk and milk is sweet",
         "there is a boy who loves cow" };
    int N = 4;
    System.out.print(countleastWords(arr, N));
  }
}
 
// This code is contributed by Samim Hossain Mondal.

Python3

# Python code for the above approach
 
# Function to find count of
# words in the given string
def countword(a) :
 
    # Stores word count
    count = 1;
    for i in range(len(a)):
 
        # If a new word is
        # encountered
        if (a[i] == ' '):
            count += 1
 
    # Return count
    return count;
 
# Function to find minimum count of
# words among all given sentences
def countleastWords(arr, N):
 
    # Stores the final answer
    ans = 10 ** 9;
 
    # Loop to iterate over sentences
    for i in range(N):
 
        # Stores count of words
        # in ith sentence
        temp = countword(arr[i]);
 
        # Update answer
        if (temp < ans):
            ans = temp;
 
    # Return Answer
    return ans;
 
# Driver code
arr = ["there is a cow",
    "cow is our mother",
    "cow gives us milk and \
                milk is sweet",
    "there is a boy who loves cow"];
N = 4;
 
print(countleastWords(arr, N));
 
# This code is contributed by gfgking

C#

// C# code to implement above approach
using System;
class GFG
{
   
    // Function to find count of
    // words in the given string
    static int countword(string a)
    {
       
        // Stores word count
        int count = 1;
        for (int i = 0; i < a.Length; i++) {
 
            // If a new word is
            // encountered
            if (a[i] == ' ')
                count++;
        }
 
        // Return count
        return count;
    }
 
    // Function to find minimum count of
    // words among all given sentences
    static int countleastWords(string[] arr, int N)
    {
       
        // Stores the final answer
        int ans = Int32.MaxValue;
 
        // Loop to iterate over sentences
        for (int i = 0; i < N; i++) {
 
            // Stores count of words
            // in ith sentence
            int temp = countword(arr[i]);
 
            // Update answer
            if (temp < ans)
                ans = temp;
        }
 
        // Return Answer
        return ans;
    }
 
    // Driver code
    public static void Main()
    {
        string[] arr
            = { "there is a cow", "cow is our mother",
                "cow gives us milk and milk is sweet",
                "there is a boy who loves cow" };
        int N = 4;
        Console.Write(countleastWords(arr, N));
    }
}
 
// This code is contributed by Samim Hossain Mondal.

Javascript

  <script>
      // JavaScript code for the above approach
 
      // Function to find count of
      // words in the given string
      function countword(a)
      {
       
          // Stores word count
          let count = 1;
          for (let i = 0; i < a.length; i++) {
 
              // If a new word is
              // encountered
              if (a[i] == ' ')
                  count++;
          }
 
          // Return count
          return count;
      }
 
      // Function to find minimum count of
      // words among all given sentences
      function countleastWords(arr, N)
      {
       
          // Stores the final answer
          let ans = Number.MAX_VALUE;
 
          // Loop to iterate over sentences
          for (let i = 0; i < N; i++) {
 
              // Stores count of words
              // in ith sentence
              let temp = countword(arr[i]);
 
              // Update answer
              if (temp < ans)
                  ans = temp;
          }
 
          // Return Answer
          return ans;
      }
       
      // Driver code
 
      let arr = ["there is a cow",
          "cow is our mother",
          "cow gives us milk and \
                    milk is sweet",
          "there is a boy who loves cow"];
      let N = 4;
 
      document.write(countleastWords(arr, N) + "<br>");
 
// This code is contributed by Potta Lokesh
  </script>
Producción

4

Complejidad de tiempo: O(N * M) donde M es el número promedio de caracteres para todas las oraciones
Espacio auxiliar: O(1) 

Publicación traducida automáticamente

Artículo escrito por sauarbhyadav 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 *