Longest Word in Dictionary through Deleting问题及解法

来源:互联网 发布:程序员和设计师 编辑:程序博客网 时间:2024/05/16 07:26

问题描述:

Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.

示例:

Input:s = "abpcplea", d = ["ale","apple","monkey","plea"]Output: "apple"
Input:s = "abpcplea", d = ["a","b","c"]Output: "a"

问题分析:

先将d排序,长度由长到短,相等时,字典序小的优先。然后遍历d中的字串,找到第一个能由s中的字符组成的字符串,这个子字串就是答案。


过程详见代码:

class Solution {public:    string findLongestWord(string s, vector<string>& d) {        sort(d.begin(), d.end(), [](string& s1, string& s2){ return s1.length() > s2.length() || (s1.length() == s2.length() && s1 < s2); });string res = "";for (auto str : d){int j = 0,i = 0;for (; j < s.length() && i < str.length();){if (s[j] == str[i]){i++;}j++;}if (i == str.length() && res.length() < i){res = str;                break;}}return res;    }};