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

📅  最后修改于: 2021-09-07 02:57:11             🧑  作者: Mango

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

例子:

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

  1. 使用字符串从句子中提取单词并将它们存储在字符串向量中。
  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


Javascript


输出:
Geeksforgeeks

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

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