LeetCode:Longest Word in Dictionary through Deleting
524. Longest Word in Dictionary through Deleting
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.
Example 1:
Input: s = "abpcplea", d = ["ale","apple","monkey","plea"] Output: "apple"
Example 2:
Input: s = "abpcplea", d = ["a","b","c"] Output: "a"
思路:题目比较简单,关键在于如何判断string s1能不能通过删除一些字符形成string s2,方法就是对于s2中的每个字符依次在s1中查找同时记录下在s1中的查找位置,直到找到该字符为止,
如果所有s2中的字符查找完毕就可以通过s1中删除一些字符形成s2.
1 bool isf(string& s,string& d) 2 { 3 int lens = s.length(); 4 int lend = d.length(); 5 int p = 0; 6 int i = 0; 7 while (p < lens&&i < lend) 8 { 9 while (p<lens && s[p] != d[i]) 10 ++p; 11 if (p == lens&&s[p] != d[i]) 12 return false; 13 ++p; ++i; 14 } 15 return i == lend; 16 } 17 string findLongestWord(string s, vector<string>& d) 18 { 19 if(s=="") 20 return ""; 21 sort(d.begin(), d.end()); 22 int size = d.size(); 23 int maxl = -1; 24 string r; 25 for (int i = 0; i < size; i++) 26 { 27 if (isf(s, d[i])) 28 { 29 int tm = d[i].length(); 30 if (tm > maxl) 31 { 32 maxl = d[i].length(); 33 r = d[i]; 34 } 35 } 36 } 37 return r; 38 }
如果你有任何疑问或新的想法,欢迎在下方评论。