JAVA O(n^2) solution


  • 0
    Q

    This shouldn't be a hard problem, but it really takes a while to understand the problem :(.

    First sort the strings by length, then use a count to check whether the string is the result.

        public int findLUSlength(String[] strs) {
            Arrays.sort(strs, new Comparator<String>() {
                @Override
                public int compare(String s1, String s2) {
                    return s2.length() - s1.length();
                }
            });
    
    
            for(String sub : strs){
                int count = 0;
                for(String str : strs){
                    if(isSubsequent(sub, str)){
                        count++;
                    }
                }
                if(count == 1){
                    return sub.length();
                }
            }
            return -1;
    
        }
    
        private boolean isSubsequent(String sub, String str){
            if(sub.equals(str)){
                return true;
            }
            int i = 0, j = 0;
            while(i < sub.length() && j < str.length()){
                if(sub.charAt(i) == str.charAt(j)){
                    i++;
                }
                j++;
            }
    
            return i == sub.length();
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.