Sorting and matching, pretty straightforward


  • 0
    M
    public class Solution {
        public String findLongestWord(String s, List<String> d) {
            if (d == null || d.size() == 0 || s == null || s.length() == 0) return "";
            Collections.sort(d, new Comparator<String>() {
                public int compare(String item1, String item2) {
                    if (item1.length() != item2.length()) return item2.length() - item1.length();
                    int i = 0, j = 0;
                    while (i < item1.length() && item1.charAt(i) == item2.charAt(j)) {
                        i++;
                        j++;
                    }
                    return i == item1.length() ? 1 : item1.charAt(i) - item2.charAt(j);
                }
            });
            for (int i = 0; i < d.size(); i++) {
                if (canGet(s, d.get(i))) return d.get(i);
            }
            return "";
        }
        
        public boolean canGet(String s, String d) {
            int j = 0;
            for (int i = 0; i < s.length(); i++) {
                if (j == d.length()) return true;
                if (s.charAt(i) == d.charAt(j)) j++;
            }
            return j == d.length();
        }
    }```

Log in to reply
 

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