最長非公共字符串 Longest Uncommon Subsequence I

問題:app

Given a group of two strings, you need to find the longest uncommon subsequence of this group of two strings. 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

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 two strings, and the output needs to be the length of the longest uncommon subsequence. If the longest uncommon subsequence doesn't exist, return -1.element

Example 1:rem

Input: "aba", "cdc"
Output: 3
Explanation: The longest uncommon subsequence is "aba" (or "cdc"), 
because "aba" is a subsequence of "aba", 
but not a subsequence of any other strings in the group of two strings.

Note:字符串

  1. Both strings' lengths will not exceed 100.
  2. Only letters from a ~ z will appear in input strings.

解決:input

【注】理解題意:若兩個字符串相等,表示它們徹底相同,沒有不一樣的子序列,返回-1。若兩個字符串有一點不一樣,則返回長度更長的那一個。string

① 直接查找。it

public class Solution {//5ms
    public int findLUSlength(String a, String b) {
        int len1 = a.length();
        int len2 = b.length();
        if(len1 != len2) return Math.max(len1,len2);
        else{
            for(int i = 0;i < len1;i ++){
                if(a.charAt(i) != b.charAt(i)) return len1;
            }
        }
        return -1;
    }
}io

② 進化版

public class Solution {//3ms
    public int findLUSlength(String a, String b) {
        if (a == null) {
            if (b == null) {
                return -1;
            }
            return b.length();
        }
        if (b == null) {
            return a.length();
        }      
        return (a.equals(b) ? -1 : Math.max(a.length(), b.length()));
    }
}

③ 最直接的作法

public class Solution { //5ms
    public int findLUSlength(String a, String b) {
        if(! a.equals(b)) return Math.max(a.length(),b.length());
        return -1;
    }
}

public class Solution { //3ms     public int findLUSlength(String a, String b) {         if (a.equals(b))             return -1;         return Math.max(a.length(), b.length());     } }

相關文章
相關標籤/搜索