LeetCode - 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.

Example 1:
Input: "aba", "cdc", "eae"
Output: 3
Note:

All the given strings' lengths will not exceed 10.
The length of the given list will be in the range of [2, 50].

不需要深入到每一个字符去遍历,因为如果整个string都是common的话,name他的substrings 肯定也是 common的。

class Solution {
    public int findLUSlength(String[] strs) {
        int res = -1;
        int j = 0;
        for (int i = 0; i < strs.length; i++) {
            for (j = 0; j < strs.length; j ++) {
                if ( i == j) {
                    continue;
                }
                if (isSub(strs[i], strs[j])) {
                    break;
                }
            }
            if (j == strs.length ) {
                res = Math.max(res, strs[i].length());
            }
        }
        return res;
    }
    
    private boolean isSub (String a, String b) {
        int i = 0;
        int j = 0;
        while (i < a.length() && j < b.length()) {
            if (a.charAt(i) == b.charAt(j)) {
                i ++;
            }
            j ++;
        }
        if (i != a.length()) {
            return false;
        }
        return true;
    }
}

 

上一篇:如何创建 Swarm 集群?- 每天5分钟玩转 Docker 容器技术(95)


下一篇:剑指 Offer 58 - I. 翻转单词顺序 + 双指针