問題:ide
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.this
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.spa
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..net
Example 1:排序
Input: "aba", "cdc", "eae" Output: 3
Note:element
解決:rem
① 暴力解決。遍歷全部的字符串,對於每一個遍歷到的字符串,再和全部的其餘的字符串比較,看是否是某一個字符串的子序列,若是都不是的話,那麼當前字符串就是一個非共同子序列,用其長度來更新結果res。字符串
class Solution { //11ms
public int findLUSlength(String[] strs) {
int res = -1;
int j = 0;
int len = strs.length;
for (int i = 0;i < len;i ++){
for (j = 0;j < len;j ++){
if (i == j) continue;
if (isSubs(strs[i],strs[j])) break;
}
if (j == len) res = Math.max(res,strs[i].length());
}
return res;
}
public boolean isSubs(String subs,String str){
int i = 0;
for (char c : str.toCharArray()){
if (c == subs.charAt(i)) i ++;
if (i == subs.length()) break;
}
return i == subs.length();
}
}get
② 按照字符串長度降序排列strs;遍歷strs,若是str不是全部strs的獨有子字符串,返回str的長度;若是沒有找到獨有字符串,返回-1。input
class Solution { //12ms
public int findLUSlength(String[] strs) {
Arrays.sort(strs, new Comparator<String>() {//按照長度從大到小排序
@Override public int compare(String o1, String o2) { return o2.length() - o1.length(); } }); for (int i = 0;i < strs.length;i ++){ int noMatches = strs.length - 1; for (int j = 0;j < strs.length;j ++){ if (i != j && isSub(strs[i],strs[j])){ noMatches --; } if (noMatches == 0){ return strs[i].length(); } } } return -1; } public boolean isSub(String s1,String s2){ int i = 0; for (char c : s2.toCharArray()){ if (i < s1.length() && s1.charAt(i) == c){ i ++; } } if (i == s1.length()){ return false; } return true; } }