Concise C++ Brute force based on previous problems


  • 1
    class Solution {
    public:
        bool validWordAbbreviation(string word, string abbr) {
            int i = 0, j = 0;
            while (i < word.size() && j < abbr.size()) {
                if (isdigit(abbr[j])) {
                    if (abbr[j] == '0') return false;
                    int val = 0;
                    while (j < abbr.size() && isdigit(abbr[j])) 
                        val = val * 10 + abbr[j++] - '0';
                    i += val;
                }
                else if (word[i++] != abbr[j++]) return false;
            }
            return i == word.size() && j == abbr.size();
        }
        
        
        void backtrack2(string& word, int begin, string str, vector<pair<int, string>>& res, int counts, int times) {
            if (begin == word.size()) {
                res.push_back({times + max(counts - 1, 0), str + (counts > 0 ? to_string(counts) : "")});
                return;
            }
            backtrack2(word, begin + 1, str, res, counts + 1, times);
            backtrack2(word, begin + 1, str + (counts > 0 ? to_string(counts) : "") + 
                        word[begin], res, 0, times + max(counts - 1, 0));
        }
    
        vector<pair<int, string>> generateAbbreviations(string& word) {
            vector<pair<int, string>> res;    
            backtrack2(word, 0, "", res, 0, 0);
            return res;
        }
    
        string minAbbreviation(string target, vector<string>& dictionary) {
            if (dictionary.empty()) return to_string((int)target.size());
            vector<pair<int, string>> abbrs = generateAbbreviations(target);
            auto comp = [](const pair<int, string>& p1, const pair<int, string>& p2){ return p1.first > p2.first; };
            sort(abbrs.begin(), abbrs.end(), comp);
            for (auto& abbr : abbrs) {
                int i = 0;
                for (; i < dictionary.size(); i++) 
                    if (validWordAbbreviation(dictionary[i], abbr.second)) break;
                if (i == dictionary.size()) return abbr.second;
            }
            return "";
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.