Find largest word in dictionary by deleting some characters of given string in C++


Consider we have a dictionary, and a string s. Find the longest string in the dictionary, that can be formed by deleting some characters of the string s. Suppose the s is “apbreoigroakml”, The dictionary has {“prog”, “ram”, “program”}, then the result will be “program”.

To solve this, we will traverse all dictionary words, and for each word, we will check whether the subsequence of the given string and is longest of all such words. Finally return longest word with given string as subsequence.

Example

#include<iostream>
#include<vector>
using namespace std;
bool isSubSequence(string s1, string s2) {
   int m = s1.length(), n = s2.length();
   int j = 0;
   for (int i=0; i<n&&j<m; i++)
   if (s1[j] == s2[i])
      j++;
   return (j==m);
}
string getLongestSubstr(vector <string > dict, string s) {
   string result = "";
   int length = 0;
   for (string word : dict) {
      if (length < word.length() && isSubSequence(word, s)) {
         result = word;
         length = word.length();
      }
   }
   return result;
}
int main() {
   vector <string > dict = {"prog", "ram", "program"};
   string str = "apbreoigroakml" ;
   cout << getLongestSubstr(dict, str) << endl;
}

Output

program

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 01-Nov-2019

121 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements