码迷,mamicode.com
首页 > 其他好文 > 详细

522 Longest Uncommon Subsequence II 最长特殊序列 II

时间:2018-04-22 21:47:24      阅读:475      评论:0      收藏:0      [点我收藏+]

标签:leetcode   ems   comm   seq   div   tor   long   public   class   

详见:https://leetcode.com/problems/longest-uncommon-subsequence-ii/description/

C++:

方法一:

class Solution {
public:
    int findLUSlength(vector<string>& strs)
    {
        int res = -1, j = 0, n = strs.size();
        for (int i = 0; i < n; ++i) 
        {
            for (j = 0; j < n; ++j)
            {
                if (i == j)
                {
                    continue;
                }
                if (checkSubs(strs[i], strs[j]))
                {
                    break;
                }
            }
            if (j == n)
            {
                res = max(res, (int)strs[i].size());
            }
        }
        return res;
    }
    int checkSubs(string subs, string str) 
    {
        int i = 0;
        for (char c : str)
        {
            if (c == subs[i])
            {
                ++i;
            }
            if (i == subs.size())
            {
                break;
            }
        } 
        return i == subs.size();
    }
};

 方法二:

class Solution {
public:
    int findLUSlength(vector<string>& strs) 
    {
        int n = strs.size();
        unordered_set<string> s;
        sort(strs.begin(), strs.end(), [](string a, string b)
             {
            if (a.size() == b.size())
            {
                return a > b;
            }
            return a.size() > b.size();
        });
        for (int i = 0; i < n; ++i)
        {
            if (i == n - 1 || strs[i] != strs[i + 1])
            {
                bool found = true;
                for (auto a : s)
                {
                    int j = 0;
                    for (char c : a) 
                    {
                        if (c == strs[i][j]) 
                        {
                            ++j;
                        }
                        if (j == strs[i].size())
                        {
                            break;
                        }
                    }
                    if (j == strs[i].size()) 
                    {
                        found = false;
                        break;
                    }
                }
                if (found) 
                {
                    return strs[i].size();
                }
            }
            s.insert(strs[i]);
        }
        return -1;
    }
};

 参考:http://www.cnblogs.com/grandyang/p/6680548.html

522 Longest Uncommon Subsequence II 最长特殊序列 II

标签:leetcode   ems   comm   seq   div   tor   long   public   class   

原文地址:https://www.cnblogs.com/xidian2014/p/8909054.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!