Java, skip the duplicate and its substring; find the max length one.


  • 0
    L
    1. reorder it based on length
    2. record the duplicated one and its substring
    3. find the longest one

    '''
    public int findLUSlength(String[] strs) {
    Arrays.sort(strs,new Comparator<String>(){
    @Override
    public int compare(String a,String b){
    return a.length()==b.length()?(a.compareTo(b)):a.length()-b.length();
    }
    });

        if(strs==null||strs.length<1) return -1;
        if(strs.length==1) return strs[0].length();
        if(strs.length==2) return (strs[0].equals(strs[1]))?0:Math.max(strs[0].length(),strs[1].length());
        
        String prev="";//strs[strs.length-1];
        ArrayList<String> strList=new ArrayList<>();
        for(int i=strs.length-1;i>=0;i--){
            System.out.println(strs[i]);
            boolean isSub=false;
            if(strList.size()>0){
                for(String str:strList){
                    if(subStringNew(str,strs[i]))//str.indexOf(strs[i])!=-1)
                    {isSub=true;strList.add(strs[i]);break;}
                }
                //System.out.println("##"+strs[i]);
                if(isSub) continue;
            }
            if(strs[i].equals(prev)) { strList.add(prev); continue;}
            else {
                prev=strs[i];
            }
        }
        for(int i=strs.length-1;i>=0;i--){
            if(strList.contains(strs[i])) continue;
            else return strs[i].length();
        }
        return -1;
            
    }
    public boolean subStringNew(String parent,String son){
        //for(int i=0;i<son.length();i++)
        int i=0,j=0;
        while(i<son.length()&&j<parent.length()){
            if(son.charAt(i)==parent.charAt(j)){i++;j++;}
            else j++;
        }
        if(i==son.length()) return true;
        else return false;
        
    }
    

    ''''


Log in to reply
 

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