
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 String Chain in C++
Suppose we have a list of words, here each word consists of lowercase letters. So one word word1 is a predecessor of another word word2 if and only if we can add exactly one letter anywhere in word1 to make it equal to word2. For the example of the predecessor is like, "abc" is a predecessor of "abac". Now a word chain is a sequence of words [word_1, word_2, ..., word_k] with k >= 1, where word_1 is a predecessor of word_2, word_2 is a predecessor of word_3, and so on. We have to find the longest possible length of a word chain with words chosen from the given list of words.
So if the input is like: ["a","b","ba","bca","bda","bdca"], then the result will be 4, as one of the longest chain will be [“a”, “ba”, “bda”, “bdca”].
To solve this, we will follow these steps −
Define a map dp, n := size of words array
sort the words array based on the length
ret := 0
-
for i in range 0 tn n – 1
best := 0
-
for j in range 0 to length of the word[i] – 1
word := (substring of words[i] from 0 to j – 1) concatenate (substring of words[i] from j + 1 to end)
best := max of best, dp[word] + 1
dp[words[i]] := best
ret := max of (ret, dp[words[i]])
return ret
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: static bool cmp(string s1, string s2){ return s1.size() < s2.size(); } int longestStrChain(vector<string>& words) { unordered_map <string, int> dp; int n = words.size(); sort(words.begin(), words.end(), cmp); int ret = 0; for(int i = 0; i < n; i++){ int best = 0; for(int j = 0; j < words[i].size(); j++){ string word = words[i].substr(0, j) + words[i].substr(j + 1); best = max(best, dp[word] + 1); } dp[words[i]] = best; ret = max(ret, dp[words[i]]); } return ret; } }; main(){ vector<string> v = {"a","b","ba","bca","bda","bdca"}; Solution ob; cout << (ob.longestStrChain(v)); }
Input
["a","b","ba","bca","bda","bdca"]
Output
4