算法作业_16(2017.4.18第九周)

来源:互联网 发布:mac系统word文档只读 编辑:程序博客网 时间:2024/06/07 06:44

522. Longest Uncommon Subsequence II

Given a list of strings, you need to find the longest uncommon subsequence among them. The longest uncommon subsequence is defined as the longest subsequence of one of these strings and this subsequence should not be any subsequence of the other strings.

A subsequence is a sequence that can be derived from one sequence by deleting some characters without changing the order of the remaining elements. Trivially, any string is a subsequence of itself and an empty string is a subsequence of any string.

The input will be a list of strings, and the output needs to be the length of the longest uncommon subsequence. If the longest uncommon subsequence doesn't exist, return -1.

题目大意:

给定一组字符串,寻找其最长不公共子序列。最长不公共子序列是指:这组字符串中某一个的子序列,该子序列不是其余任意字符串的子序列,并且长度最长。

子序列是指从一个序列中删除一些字符,剩余字符顺序保持不变得到的新序列。任何字符串都是其本身的子序列,空串不属于任意字符串的子序列。

返回最长不公共子序列,若不存在,返回-1。

解法一:遍历所有的字符串,对于每个遍历到的字符串,再和所有的其他的字符串比较,看是不是某一个字符串的子序列,如果都不是的话,那么当前字符串就是一个非共同子序列,用其长度来更新结果res,参见代码如下:

class Solution {public:    int findLUSlength(vector<string>& strs) {        int res = -1,n=strs.size();        int j = 0;        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 sub,string strs){       int i = 0 ;       for(char c :strs){           if(c==sub[i]){               i++;           }           if(i==sub.size()){               break;           }       }       return i==sub.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;    }};



0 0