
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
Advertisements