程式語言 - LeetCode - C++ - 524. Longest Word in Dictionary through Deleting



題目:


解答:

class Solution {
public:
    string findLongestWord(string s, vector<string>& dictionary) {
        auto is_seq = [](string a, string b) {
            int i = 0;
            int j = 0;

            while (i < a.size() && j < b.size()) {
                if (a[i] == b[j]) {
                    i += 1;
                }
                j += 1;
            }

            return i == a.size();
        };

        string ans = "";
        for (string word : dictionary) {
            if (is_seq(word, s)) {
                if (word.size() > ans.size()) {
                    ans = word;
                }
                else if (word.size() == ans.size() && word < ans) {
                    ans = word;
                }
            }
        }

        return ans;
    }
};