📌  相关文章
📜  从以给定单词为前缀的给定句子中查找单词

📅  最后修改于: 2021-04-23 16:19:19             🧑  作者: Mango

给定一个代表句子的字符串S和另一个字符串,任务是从S中找到以字符串作为前缀的单词。如果字符串没有这样的单词,则打印-1

例子:

方法:按照以下步骤查找哪个单词具有给定的前缀:

  1. 使用stringstream从句子中提取单词,并将其存储在字符串向量中。
  2. 现在,遍历数组并检查哪个单词包含给定单词作为其自己的前缀。
  3. 如果发现任何单词都是正确的,则打印该单词。否则,如果找不到这样的单词,请打印-1

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find the position
// of the string having word as prefix
string isPrefixOfWord(string sentence,
                      string Word)
{
    stringstream ss(sentence);
 
    // Initialize a vector
    vector v;
    string temp;
 
    // Extract words from the sentence
    while (ss >> temp) {
        v.push_back(temp);
    }
 
    // Traverse each word
    for (int i = 0; i < v.size(); i++) {
 
        // Traverse the characters of word
        for (int j = 0; j < v[i].size(); j++) {
 
            // If prefix does not match
            if (v[i][j] != Word[j])
                break;
 
            // Otherwise
            else if (j == Word.size() - 1)
 
                // Return  the word
                return v[i];
        }
    }
 
    // Return -1 if not present
    return "-1";
}
 
// Driver code
int main()
{
    string s = "Welcome to Geeksforgeeks";
    string word = "Gee";
 
    cout << isPrefixOfWord(s, word) << endl;
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
import java.io.*;
import java.lang.Math;
 
class GFG{
      
// Function to find the position
// of the string having word as prefix
static String isPrefixOfWord(String sentence,
                             String Word)
{
    String a[] = sentence.split(" ");
   
    // Initialize an ArrayList
    ArrayList v = new ArrayList<>();
     
    // Extract words from the sentence
    for(String e : a)
        v.add(e);
     
    // Traverse each word
    for(int i = 0; i < v.size(); i++)
    {
         
        // Traverse the characters of word
        for(int j = 0; j < v.get(i).length(); j++)
        {
             
            // If prefix does not match
            if (v.get(i).charAt(j) != Word.charAt(j))
                break;
                 
            // Otherwise
            else if (j == Word.length() - 1)
             
                // Return  the word
                return v.get(i);
        }
    }
     
    // Return -1 if not present
    return "-1";
}
 
// Driver code 
public static void main(final String[] args)
{
    String s = "Welcome to Geeksforgeeks";
    String word = "Gee";
   
    System.out.println(isPrefixOfWord(s, word));
}
}
 
// This code is contributed by bikram2001jha


Python3
# Python3 program for the
# above approach
 
# Function to find the
# position of the string
# having word as prefix
def isPrefixOfWord(sentence, word):
   
    a=sentence.split(" ")
 
    # Initialize an List
    v = []
 
    # Extract words from
    # the sentence
    for i in a:
        v.append(i)
 
    # Traverse each word
    for i in range(len(v)):
 
        # Traverse the characters of word
        for j in range(len(v[i])):
 
            # If prefix does not match
            if(v[i][j] != word[j]):
                break
 
            # Otherwise
            elif(j == len(word) - 1):
 
                # Return  the word
                return v[i]
 
    # Return -1 if not present
    return -1
 
# Driver code
s = "Welcome to Geeksforgeeks"
word = "Gee"
print(isPrefixOfWord(s, word))
 
# This code is contributed by avanitrachhadiya2155


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
      
// Function to find the position
// of the string having word as prefix
static String isPrefixOfWord(String sentence,
                             String Word)
{
  String []a = sentence.Split(' ');
 
  // Initialize an List
  List v = new List();
 
  // Extract words from the sentence
  foreach(String e in a)
    v.Add(e);
 
  // Traverse each word
  for(int i = 0; i < v.Count; i++)
  {
    // Traverse the characters of word
    for(int j = 0; j < v[i].Length; j++)
    {
      // If prefix does not match
      if (v[i][j] != Word[j])
        break;
 
      // Otherwise
      else if (j == Word.Length - 1)
 
        // Return  the word
        return v[i];
    }
  }
 
  // Return -1 if not present
  return "-1";
}
 
// Driver code 
public static void Main(String[] args)
{
  String s = "Welcome to Geeksforgeeks";
  String word = "Gee";
  Console.WriteLine(isPrefixOfWord(s, word));
}
}
 
// This code is contributed by Rajput-Ji


输出:
Geeksforgeeks





时间复杂度: O(L),其中L表示字符串S的长度
辅助空间: O(L)