Not clean but straight forward solution


  • 0
    J

    public class Solution {

    public String findLongestWord(String s, List<String> d) {
        if (s.length() == 0) return new String();
        List<String> valid = new ArrayList<>();
        int maxLen = 0;
        for (String i : d) {
            if (check(s, i)) {
                maxLen = maxLen > i.length() ? maxLen : i.length();
                valid.add(i);
            }
        }
        // System.out.println(maxLen);
        PriorityQueue<String> q = new PriorityQueue<>();
        for (String i : valid) {
            if (i.length() == maxLen) q.add(i);
        }
        if (q.size() == 0) return new String();
        return q.peek();
    }
    
    public boolean check(String t, String s) {
        if (s.length() == 0) return true;
        if (t.length() == 0) return false;
        int p = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            p = t.indexOf(c, p);
            if (p == -1) return false;
            p++;
        }
        
        return true;
    }
    

    }


Log in to reply
 

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