524. Longest Word in Dictionary through Deleting
Medium
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"
Note:
- All the strings in the input will only contain lower-case letters.
- The size of the dictionary won't exceed 1,000.
- The length of all the strings in the input won't exceed 1,000.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | class Solution { struct comp{ bool operator()(const string &s1, const string &s2){ if(s1.size()==s2.size()){ return s1 < s2; }else{ return s1.size()>s2.size(); } } }; comp c; public: string findLongestWord(string s, vector<string>& d) { sort(d.begin(), d.end(), c); for(auto w:d){ int i = 0, j = 0; while(i<s.size() && j<w.size()){ if(s[i]!=w[j]) i++; else{i++; j++;} } if(j == w.size()) return w; } return ""; } }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //Java class Solution { public String findLongestWord(String s, List<String> d) { String ret = ""; for(String w : d){ int i=0, j=0; while(i<s.length() && j<w.length()){ if(s.charAt(i)==w.charAt(j)) j++; i++; } if(j==w.length() && w.length()>=ret.length()){ if(w.length()>ret.length() || w.compareTo(ret)<0) ret = w; } } return ret; } } |
No comments:
Post a Comment