720. Longest Word in Dictionary (Brute Force)

class Solution { public: bool findpart(vector<string> & words, string part){ // input a part of a word, check if it's in the vector... for (auto & word : words){ if (word == part) return true; } return false; } string longestWord(vector<string>& words) { vector<string> res; // store all the words that satisfies the "part in this vector" condiion for (auto & word : words){ size_t size = word.size(); bool found = true; for (size_t i = 1; i <= word.size(); i++){ string part = word.substr(0, i); if (!findpart(words, part)){ found = false; break; } } if (found) res.push_back(word); } string longest = res.front(); for (auto & r: res){ if (r.size() > longest.size() || (r.size() == longest.size() && r < longest) ) longest = r; } return longest; } };
Mistakes:
- String API: how to use string::substr()? Note the second argument is the length of the substring... npos = number of positions.
- Note to use size()
- In the end also need to compare which word is before another word...

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.