Given a list of strings words representing an English Dictionary, find the longest word in words that can be built one character at a time by other words in words. If there is more than one possible answer, return the longest word with the smallest lexicographical order.
If there is no answer, return the empty string.
Example:
Input:
words = ["w","wo","wor","worl", "world"]
Output: "world"
Explanation:
The word "world" can be built one character at a time by "w", "wo", "wor", and "worl".Approach:
C++
#include <bits/stdc++.h>using namespace std;string longestWord(vector<string> &words){sort(words.begin(), words.end());string result = "";set<string> builtWords;for (auto w : words){//if current words length is 1 or//current words is found in the setif (w.length() == 1 ||builtWords.find(w.substr(0, w.length() - 1))!= builtWords.end()){//if length of current word is more then//the length of result then//update resultif (w.length() > result.length()){result = w;}//insert current word into the setbuiltWords.insert(w);}}return result;}int main(){vector<string> words = {"w", "wo", "wor", "worl", "world"};cout << longestWord(words);return 0;}
No comments:
Post a Comment