522. Longest Uncommon Subsequence II

来源:互联网 发布:windows下启动nginx 编辑:程序博客网 时间:2024/05/22 15:25

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.

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.

Example 1:

Input: "aba", "cdc", "eae"Output: 3

Note:

  1. All the given strings' lengths will not exceed 10.

  1. The length of the given list will be in the range of [2, 50].

思路:2个trick
 * 1. 答案是字符串数组中的一个
 * 2. 先按照长度排序

package l522;import java.util.Arrays;import java.util.Comparator;/* * 2个trick * 1. 答案是字符串数组中的一个 * 2. 先按照长度排序 */public class Solution {    public int findLUSlength(String[] strs) {        Arrays.sort(strs, new Comparator<String>(){@Overridepublic int compare(String o1, String o2) {return o2.length() - o1.length();}        });                for(int i=0; i<strs.length; i++) {        boolean f = false;        for(int j=0; j<strs.length; j++) {        if(i == j)continue;        if(strs[i].length() > strs[j].length()) continue;        if(isPardime(strs[i], strs[j])) {        f = true;        break;        }        }                if(!f)return strs[i].length();        }                return -1;    }        private boolean isPardime(String s1, String s2) {    int p = 0;    for(int i=0; i<s1.length(); i++) {    while(p<s2.length() && s2.charAt(p) != s1.charAt(i))    p++;    if(p == s2.length())return false;    p++;    }return true;    }}


原创粉丝点击