Home LeetCode - 524. Longest Word in Dictionary through Deleting
Post
Cancel

LeetCode - 524. Longest Word in Dictionary through Deleting

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.

제한사항

  • 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
Example 1:

Input:
s = "abpcplea", d = ["ale","apple","monkey","plea"]

Output: 
"apple"
1
2
3
4
5
6
7
Example 2:

Input:
s = "abpcplea", d = ["a","b","c"]

Output: 
"a"

풀이

  • Array, Sort
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
26
27
28
29
30
31
32
33
class Solution {
public:
    string findLongestWord(string s, vector<string>& d) {
        std::vector<std::string> items;
        
        for (const std::string& str : d) {
            int sIndex = 0;
            int strIndex = 0;
            
            while (sIndex < s.size() && strIndex < str.size()) {
                if (s[sIndex] == str[strIndex]) {
                    ++sIndex;
                    ++strIndex;
                } else {
                    ++sIndex;                    
                }
                
                if (strIndex == str.size()) {
                    items.emplace_back(str);
                }
            }
        }

        std::sort(items.begin(), items.end(), [](const std::string& a, const std::string& b) {
            if (a.size() == b.size()) {
                return a < b;
            }
            return a.size() > b.size();
        });

        return items.empty() ? "" : items[0];
    }
};
This post is licensed under CC BY 4.0 by the author.