Longest Word in Dictionary

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<stringbuiltWords;
    for (auto w : words)
    {
        //if current words length is 1 or
        //current words is found in the set
        if (w.length() == 1 ||
            builtWords.find(w.substr(0w.length() - 1)) 
!= builtWords.end())
        {
            //if length of current word is more then
            //the length of result then
            //update result
            if (w.length() > result.length())
            {
                result = w;
            }

            //insert current word into the set
            builtWords.insert(w);
        }
    }
    return result;
}

int main()
{
    vector<stringwords = {"w""wo""wor""worl""world"};

    cout << longestWord(words);

    return 0;
}


No comments:

Post a Comment