C++ AC Solution using map


  • -1
    class Solution {
    public:
        struct cmpByStringLength {
            bool operator()(const std::string& a, const std::string& b) const {
                return a.length() == b.length() ? a > b : a.length() > b.length();
            }
        };
    
        int findLUSlength(vector<string>& strs) {
            map<string, int, cmpByStringLength> words;
            for (auto s : strs) words[s]++;
            int len = -1;
            for (auto p : words) {
                if (p.second == 1 && isNotSubstring(words, p.first)){
                    int l = p.first.length();
                    if (l > len) return l;
                }
            }
            
            return len;
        }
        
        bool isNotSubstring (const map<string, int, cmpByStringLength>& words, const string& s) {
            auto end = words.find(s);
            for (auto it = words.begin(); it != end; it++) {
                int i = 0, j = 0;
                while (i < s.length() && j < it->first.length()) {
                    if (s[i] == it->first[j++]) i++;
                }
                if (i == s.length()) return false;
            }
            return true;
        }
    };
    

Log in to reply
 

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