-
SLPHPython:贪心算法 + 广度优先搜索
class Solution(object): def findLongestWord(self, s, d): """ :type s: str :type d: List[str] :rtype: str """ ans = [] dmap = collections.defaultdict(list) for w in d: dmap[w[0]].append((0, w)) for c in s: wlist = dmap[c] del dmap[c] for i, w in wlist: if i + 1 == len(w): ans.append(w) else: dmap[w[i + 1]].append((i + 1, w)) if not ans: return '' maxl = len(max(ans, key = len)) return min(w for w in ans if len(w) == maxl)
-
SLPHC++解法一:
class Solution { public: string findLongestWord(string s, vector<string>& d) { sort(d.begin(), d.end(), [](string a, string b){ if (a.size() == b.size()) return a < b; return a.size() > b.size(); }); for (string str : d) { int i = 0; for (char c : s) { if (i < str.size() && c == str[i]) ++i; } if (i == str.size()) return str; } return ""; } };
-
SLPHC++解法二:
class Solution { public: string findLongestWord(string s, vector<string>& d) { string res = ""; for (string str : d) { int i = 0; for (char c : s) { if (i < str.size() && c == str[i]) ++i; } if (i == str.size() && str.size() >= res.size()) { if (str.size() > res.size() || str < res) { res = str; } } } return res; } };
-