Longest Word in Dictionary through Deleting in C++


Suppose we have a string and a string dictionary, we have to find the longest string in the dictionary that can be formed by deleting some of the characters of the given string. If there are more than one possible results, then just return the longest word with the smallest lexicographical order. If there is no result, then return a blank string. So if the input is like “abpcplea” and d = [“ale”, “apple”, “monkey”, “plea”], then the result will be “apple”.

To solve this, we will follow these steps −

  • Define a method called isSubsequence(). This will take s1 and s2
  • j := 0
  • for i in range 0 to size of s1
    • if s2[j] = s1[i], then increase j by 1
    • if j = size of s2, then break the loop
  • return true if j = size of s2
  • From the main method, do the following −
  • ans := a blank string
  • for i in range 0 to size of d – 1
    • x := d[i]
    • if size of x > size of ans or size of x = size of ans and x < ans, then
      • if isSubsequence(s, x) is true, then ans := x
  • return ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   bool isSubsequence(string s1, string s2){
      int j =0;
      for(int i = 0; i < s1.size(); i++){
         if(s2[j] == s1[i]){
            j++;
            if(j == s2.size()) break;
         }
      }
      return j == s2.size();
   }
   string findLongestWord(string s, vector<string>& d) {
      string ans = "";
      for(int i = 0; i < d.size(); i++){
         string x = d[i];
         if(x.size() > ans.size() || (x.size() == ans.size() && (x < ans))){
            if(isSubsequence(s, x)) ans = x;
         }
      }
      return ans;
   }
};
main(){
   vector<string> v = {"ale","apple","monkey","plea"};
   Solution ob;
   cout << (ob.findLongestWord("abpcplea", v));
}

Input

"abpcplea"
["ale","apple","monkey","plea"]

Output

apple

Updated on: 02-May-2020

117 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements