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