Longest Uncommon Subsequence
Problem 1: Given two strings, find the longest uncommon subsequence of these two strings. Uncommon subsequence is defined as the subsequence of either one of these two strings that is not the subsequence of the other string.
Solution:
1. If these two strings is same, then no such subsequence.
2. The longer one can not be any subsequnce of the shorter one as there's no enough characters in the shorter one.
3. If the length of these two strings are not equal, and if they are different, any one of them can be the longest subsequence.
Code:
public class Solution { public int findLUSlength(String a, String b) { if(a.equals(b)) return -1; return Math.max(a.length(), b.length()); } }
Problem 2: Given a list of strings, find the longest uncommon subsequence of these strings.
Solution:
1. The problem is that the longest one might be duplicated and the shorter one might be subsequence of the longer duplicated ones.
2. Sort the array according to the length of each string using Arrays.sort(arr, Comparator.comparingInt(String::length))), this is a Java 8 expression. comparingInt method returns a comparator and needs a key exreaction function as parameter and this function should return an Integer as the comparing key. String is the type of the comparing elements and length is the function -> a.length(). Then this array will be in ascending order by length of each String.
3. From the end of the array, if there is no duplicate and the current one is not any subsequence of its following ones, then we can return the length of it.
4. To see if a shorter string is the subsequence of a longer string, we can use two pointer, the first one scans the shorter one and the second one scans the longer one. Once the character get same, we let the first one increase, otherwise, we let the second one increase. Once the shorter one reaches the length of the shorter string, we know that the shorter one is the subsequence of the longer one.
Code:
public class Solution { public int findLUSlength(String[] strs) { Map<String, Boolean> occurs = new HashMap<>(strs.length); for(String s : strs){ if(!occurs.containsKey(s)) occurs.put(s, true); else occurs.put(s, false); } Arrays.sort(strs, Comparator.comparingInt(String::length)); for(int i = strs.length-1; i >= 0; i--){ if(occurs.get(strs[i]) && !isSubsequenceOfPrev(strs, i)) return strs[i].length(); } return -1; } private boolean isSubsequenceOfPrev(String[] strs, int index){ for(int i = index+1; i < strs.length; i++){ if(isSubsequence(strs[i], strs[index])) return true; } return false; } private boolean isSubsequence(String longer, String shorter){ int j = 0; for(int i = 0; i < longer.length(); i++){ if(j==shorter.length()) return true; if(shorter.charAt(j) == longer.charAt(i)) j++; } return j==shorter.length(); } }

浙公网安备 33010602011771号