Using HashMap but its cluttered


  • 0
    D

    public class Solution {

    private static boolean subseq(String s,String p)
    {
        int i = 0, j = 0;
        while (i < s.length() && j < p.length()) {
            if (s.charAt(i) == p.charAt(j)) {
                i++; j++;
            }
            else {
                i++;
            }
        }
        return j == p.length();
    }
    
    public String findLongestWord(String s, List<String> d) {
        
       
        
        StringBuffer sb = new StringBuffer();
        int max=0;
        char [] ch = s.toCharArray();
        
        
        int count=0;
        
        for(String s1:d)
        {
            count=0;
           Map<Character, Integer> mp = new LinkedHashMap<Character,Integer>();
           for(char c:ch)
        {
            mp.put(c,mp.getOrDefault(c,0)+1);
           
        }
         if(!subseq(s,s1))
                {
                    count=1;
                   
                }
                else{
            for(int i=0;i<s1.length();i++)
            {
                if(!mp.containsKey(s1.charAt(i))||mp.get(s1.charAt(i))<=0)
                {count=1;
                   // d.remove(s1);
                    break;
                }
                
                else
                {
                   mp.put(s1.charAt(i),mp.get(s1.charAt(i))-1);  
                }
            }
            
            
                }
            
            
            
            if(count==0){
            System.out.println(s1);
            if(s1.length()>max)
            {
                if(sb.length()!=0)
                {
                   sb.setLength(0);
                }
                max=s1.length();
                sb.append(s1);
            }
            else if (s1.length()==max)
            {
                if(sb.length()!=0)
                {
                   
                System.out.print("inside");
                int a = s1.compareTo(sb.toString());
                
                 if(a<0)
                 { sb.setLength(0);
                 sb.append(s1);
                 }
                }
            }
        }
        }
        return sb.toString();
    }
    

    }


Log in to reply
 

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