Advertisement
1988coder

522. Longest Uncommon Subsequence II

Jan 5th, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.65 KB | None | 0 0
  1.  
  2. // LeetCode URL: https://leetcode.com/problems/longest-uncommon-subsequence-ii/
  3. import java.util.Arrays;
  4.  
  5. /**
  6.  * Sorting + Checking isSubsequence
  7.  *
  8.  * Time Complexity: Sort = O(N log N). each isSubsequence call takes O(X). Thus
  9.  * total conplexity = O(N log N + N^2 * X) = O(N^2 * X)
  10.  *
  11.  * Space Complexity: O(1)
  12.  *
  13.  * N = Number of strings in strs array. X = average length of the strings.
  14.  */
  15. class Solution {
  16.     public int findLUSlength(String[] strs) {
  17.         if (strs == null || strs.length == 0) {
  18.             return -1;
  19.         }
  20.         if (strs.length == 1) {
  21.             return strs[0].length();
  22.         }
  23.  
  24.         Arrays.sort(strs, (a, b) -> (b.length() - a.length()));
  25.  
  26.         for (int i = 0; i < strs.length; i++) {
  27.             boolean flag = false;
  28.             for (int j = 0; j < strs.length; j++) {
  29.                 if (strs[i].length() > strs[j].length()) {
  30.                     break;
  31.                 }
  32.                 if (i == j) {
  33.                     continue;
  34.                 }
  35.                 if (isSubsequence(strs[i], strs[j])) {
  36.                     flag = true;
  37.                     break;
  38.                 }
  39.             }
  40.             if (!flag) {
  41.                 return strs[i].length();
  42.             }
  43.         }
  44.  
  45.         return -1;
  46.     }
  47.  
  48.     private boolean isSubsequence(String s, String t) {
  49.         int indexS = 0;
  50.         for (int indexT = 0; indexT < t.length(); indexT++) {
  51.             if (s.charAt(indexS) == t.charAt(indexT)) {
  52.                 indexS++;
  53.             }
  54.             if (indexS == s.length()) {
  55.                 return true;
  56.             }
  57.         }
  58.         return false;
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement