Longest Uncommon Subsequence II using C++
public:
    unordered_set<string> dups; // set used to store duplicates
    int L; // Size of input vector
    
    // This method populates dups with elements which have more than one occurence
    void findDups(vector<string>& s) {
        for(int i=1;i<L;i++)
        {
            if(s[i-1] == s[i])
                dups.insert(s[i]);
        }
    }
    
    // This method creates a new vector u which contains unique elements of input
    void populateUnique(vector<string>& u, vector<string>& s) {
        for(int i=0;i<L;i++)
            if(dups.count(s[i]) == 0)
                u.push_back(s[i]);
        unordered_set<string>::iterator it;
        for(it=dups.begin();it!=dups.end();it++)
            u.push_back(*it);
    }
    
    // This method returns true if string a is a subsequence of string b 
    bool isSubsequence(string a, string b) {
		// a_pointer, b_pointer, a_length, b_length
        int ap = 0, bp = 0, al = a.length(), bl = b.length();
        while(ap<al && bp<bl)
        {
            if(a[ap] == b[bp])
            {
                ap++; bp++;
            }
            else
                bp++;
        }
        if(ap == al)
            return true;
        return false;
    }
    
    int findLUSlength(vector<string>& strs) {
        L = strs.size();
        
        // sorting the array lexicographically as that helps in finding duplicates
        sort(strs.begin(), strs.end());
        findDups(strs);
        
        vector<string> unique;
        populateUnique(unique,strs);
        
        // Sort the array with length of elements
        sort(unique.begin(), unique.end(), [](string a, string b){return a.length() < b.length();});
        
        for(int i=unique.size()-1;i>=0;i--)
        {
            if(dups.count(unique[i]) > 0)
                continue;
            bool found = false;
            for(int j=unique.size()-1;j>=0;j--)
            {
                cout<<unique[j]<<" ";
                if(i!=j)
                {
                    if(isSubsequence(unique[i],unique[j]))
                        found = true;
                }
            }
            if(!found)
                return unique[i].length();
        }
        return -1;
    }
};
Comments (0)