Longest Word Chain
This is a TwoSigma OA question.
#include <iostream>
#include <unordered_map>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int helper(const string& s, unordered_map<string,int>& word_map){
int longest = 1;
string short_str;
for(size_t i = 0; i < s.size(); ++i){
short_str = s.substr(0, i) + s.substr(i + 1);
if(word_map.count(short_str)){
longest = max(longest, word_map[short_str] + 1);
}
}
return longest;
}
int longest_chain(vector<string>& words){
if(words.empty()) return 0;
int n = words.size();
sort(words.begin(), words.end(), [](const string& a, const string& b) {
return a.length() < b.length();
});
unordered_map<string,int> word_map;
word_map[words[0]] = 1;
int longest = 1;
for(const string& s : words){
int curLen = helper(s, word_map);
longest = max(longest, curLen);
word_map[s] = curLen;
}
return longest;
}
int main() {
cout<<"Hello" << endl;
vector<string> input1({"a", "b", "ba", "bca", "bda", "bdca"});
int res1 = longest_chain(input1);
cout << res1 << endl;
vector<string> input2({"a", "zxb", "ba", "bca", "bda", "bdca", "zxbe", "azxbe", "azxpbe"});
cout << longest_chain(input2) << endl;
return 0;
}Last updated