📌  相关文章
📜  通过删除给定字符串的某些字符来查找字典中的最大单词

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

通过删除给定字符串的某些字符来查找字典中的最大单词

给定一个字典和一个字符串'str',找到字典中最长的字符串,它可以通过删除给定'str'的一些字符来形成。
例子:

Input : dict = {"ale", "apple", "monkey", "plea"}   
        str = "abpcplea"  
Output : apple 

Input  : dict = {"pintu", "geeksfor", "geeksgeeks", 
                                        " forgeek"} 
         str = "geeksforgeeks"
Output : geeksgeeks

被问到:谷歌面试

这个问题简化为查找一个字符串是否是另一个字符串的子序列。我们遍历所有字典单词,对于每个单词,我们检查它是否是给定字符串的子序列并且是所有此类单词中最大的。我们最终返回给定字符串的最长单词作为子序列。
下面是上述想法的实现

C++
// C++ program to find largest word in Dictionary
// by deleting some characters of given string
#include 
using namespace std;
 
// Returns true if str1[] is a subsequence of str2[].
// m is length of str1 and n is length of str2
bool isSubSequence(string str1, string str2)
{
    int m = str1.length(), n = str2.length();
 
    int j = 0; // For index of str1 (or subsequence
 
    // Traverse str2 and str1, and compare current
    // character of str2 with first unmatched char
    // of str1, if matched then move ahead in str1
    for (int i = 0; i < n && j < m; i++)
        if (str1[j] == str2[i])
            j++;
 
    // If all characters of str1 were found in str2
    return (j == m);
}
 
// Returns the longest string in dictionary which is a
// subsequence of str.
string findLongestString(vector dict, string str)
{
    string result = "";
    int length = 0;
 
    // Traverse through all words of dictionary
    for (string word : dict) {
        // If current word is subsequence of str and is
        // largest such word so far.
        if (length < word.length()
            && isSubSequence(word, str)) {
            result = word;
            length = word.length();
        }
    }
 
    // Return longest string
    return result;
}
 
// Driver program to test above function
int main()
{
    vector dict
        = { "ale", "apple", "monkey", "plea" };
    string str = "abpcplea";
    cout << findLongestString(dict, str) << endl;
    return 0;
}


Java
// Java program to find largest
// word in Dictionary by deleting
// some characters of given String
 
import java.util.*;
 
class GFG
{
 
    // Returns true if str1[] is a
    // subsequence of str2[]. m is
    // length of str1 and n is length of str2
    static boolean isSubSequence(String str1,
                                String str2)
    {
        int m = str1.length(), n = str2.length();
 
        int j = 0; // For index of str1 (or subsequence)
 
        // Traverse str2 and str1, and compare current
        // character of str2 with first unmatched char
        // of str1, if matched then move ahead in str1
        for (int i = 0; i < n && j < m; i++)
        {
            if (str1.charAt(j) == str2.charAt(i))
            {
                j++;
            }
        }
 
        // If all characters of str1
        // were found in str2
        return (j == m);
    }
 
// Returns the longest String
// in dictionary which is a
// subsequence of str.
    static String findLongestString(Vector dict,
                                            String str)
    {
        String result = "";
        int length = 0;
 
        // Traverse through all words of dictionary
        for (String word : dict)
        {
             
            // If current word is subsequence of str
            // and is largest such word so far.
            if (length < word.length() &&
                isSubSequence(word, str))
            {
                result = word;
                length = word.length();
            }
        }
 
        // Return longest String
        return result;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String[] arr = {"ale", "apple", "monkey", "plea"};
        Vector dict = new Vector(Arrays.asList(arr));
        String str = "abpcplea";
        System.out.println(findLongestString(dict, str));
    }
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program to find largest word in Dictionary
# by deleting some characters of given string
 
# Returns true if str1[] is a subsequence of str2[].
# m is length of str1 and n is length of str2
def isSubSequence(str1, str2):
 
    m = len(str1);
    n = len(str2);
 
    j = 0; # For index of str1 (or subsequence
 
    # Traverse str2 and str1, and compare current
    # character of str2 with first unmatched char
    # of str1, if matched then move ahead in str1
    i = 0;
    while (i < n and j < m):
        if (str1[j] == str2[i]):
            j += 1;
        i += 1;
 
    # If all characters of str1 were found in str2
    return (j == m);
 
# Returns the longest string in dictionary which is a
# subsequence of str.
def findLongestString(dict1, str1):
    result = "";
    length = 0;
 
    # Traverse through all words of dictionary
    for word in dict1:
         
        # If current word is subsequence of str and is largest
        # such word so far.
        if (length < len(word) and isSubSequence(word, str1)):
            result = word;
            length = len(word);
 
    # Return longest string
    return result;
 
# Driver program to test above function
 
dict1 = ["ale", "apple", "monkey", "plea"];
str1 = "abpcplea" ;
print(findLongestString(dict1, str1));
     
# This code is conribued by mits


C#
// C# program to find largest
// word in Dictionary by deleting
// some characters of given String
using System;
using System.Collections.Generic;
 
class GFG
{
 
    // Returns true if str1[] is a
    // subsequence of str2[]. m is
    // length of str1 and n is length of str2
    static bool isSubSequence(String str1,
                                String str2)
    {
        int m = str1.Length, n = str2.Length;
 
        int j = 0; // For index of str1 (or subsequence)
 
        // Traverse str2 and str1, and compare current
        // character of str2 with first unmatched char
        // of str1, if matched then move ahead in str1
        for (int i = 0; i < n && j < m; i++)
        {
            if (str1[j] == str2[i])
            {
                j++;
            }
        }
 
        // If all characters of str1
        // were found in str2
        return (j == m);
    }
 
    // Returns the longest String
    // in dictionary which is a
    // subsequence of str.
    static String findLongestString(List dict,
                                            String str)
    {
        String result = "";
        int length = 0;
 
        // Traverse through all words of dictionary
        foreach (String word in dict)
        {
             
            // If current word is subsequence of str
            // and is largest such word so far.
            if (length < word.Length &&
                isSubSequence(word, str))
            {
                result = word;
                length = word.Length;
            }
        }
 
        // Return longest String
        return result;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        String[] arr = {"ale", "apple", "monkey", "plea"};
        List dict = new List(arr);
        String str = "abpcplea";
        Console.WriteLine(findLongestString(dict, str));
    }
}
 
// This code contributed by Rajput-Ji


PHP


Javascript


C++
// C++ program to find largest word in Dictionary
// by deleting some characters of given string
#include 
using namespace std;
    string res="";
    void check(string d,string s)
    {
        int i=0;
        int j=0;
        while(i d,string S) {
     //sort the dictionary word
     // for smallest lexicographical order
      
     sort(d.begin(),d.end());
     for(string c:d)
     {
         check(c,S);
     }
     return res;
    }
// Driver program
int main()
{
    vector dict
        = { "ale", "apple", "monkey", "plea" };
    string str = "abpcplea";
    cout << LongestWord(dict, str) << endl;
    return 0;
}


Python3
# Python3 program to find largest word in Dictionary
# by deleting some characters of given string
 
res=""
 
def check(d,s):
    global res
    i = 0
    j = 0
    while(i < len(d) and j < len(s)):
 
        if(d[i] == s[j]):
            i += 1
            j += 1
        else:
            j += 1
 
        if(i == len(d) and len(res) < len(d)):
            res = d
 
def LongestWord(d, S):
   
    # sort the dictionary word
    # for smallest lexicographical order  
    d.sort()
 
    for c in d :
        check(c,S)
     
    return res
 
# Driver program
dict = [ "ale", "apple", "monkey", "plea" ]
str = "abpcplea"
print(LongestWord(dict, str))
 
# This code is contributed by shinjanpatra


Javascript


输出:

apple

时间复杂度: O(N*(K+n)) 这里 N 是字典的长度,n 是给定字符串'str' 的长度,K - 字典中单词的最大长度。
辅助空间: O(1)

一个有效的解决方案是我们对字典中的单词进行排序。我们遍历所有字典单词,对于每个单词,我们检查它是否是给定字符串的子序列,最后我们检查这个子序列是所有这些子序列中最大的。我们最终返回给定字符串的最长单词作为子序列。

C++

// C++ program to find largest word in Dictionary
// by deleting some characters of given string
#include 
using namespace std;
    string res="";
    void check(string d,string s)
    {
        int i=0;
        int j=0;
        while(i d,string S) {
     //sort the dictionary word
     // for smallest lexicographical order
      
     sort(d.begin(),d.end());
     for(string c:d)
     {
         check(c,S);
     }
     return res;
    }
// Driver program
int main()
{
    vector dict
        = { "ale", "apple", "monkey", "plea" };
    string str = "abpcplea";
    cout << LongestWord(dict, str) << endl;
    return 0;
}

Python3

# Python3 program to find largest word in Dictionary
# by deleting some characters of given string
 
res=""
 
def check(d,s):
    global res
    i = 0
    j = 0
    while(i < len(d) and j < len(s)):
 
        if(d[i] == s[j]):
            i += 1
            j += 1
        else:
            j += 1
 
        if(i == len(d) and len(res) < len(d)):
            res = d
 
def LongestWord(d, S):
   
    # sort the dictionary word
    # for smallest lexicographical order  
    d.sort()
 
    for c in d :
        check(c,S)
     
    return res
 
# Driver program
dict = [ "ale", "apple", "monkey", "plea" ]
str = "abpcplea"
print(LongestWord(dict, str))
 
# This code is contributed by shinjanpatra

Javascript