Share my java solution (without sorting)


  • 0
    C
    public String findLongestWord(String s, List<String> d) {
        String res = "";
        if (s.length() == 0 || d.size() == 0)
            return "";
        int maxLen = 0;
        for (String tmp : d) {
            if (checkWord(s, tmp)) {
                int len = tmp.length();
                if (len > maxLen) {
                    maxLen = len;
                    res = tmp;
                } else if (len == maxLen)
                    if (tmp.compareTo(res) < 0)
                        res = tmp;
            }
        }
        return res;
    }
    
    private boolean checkWord(String s, String d) {
        int sP = 0;
        int dP = 0;
        while (sP < s.length() && dP < d.length()) {
            if (s.charAt(sP) == d.charAt(dP)) {
                sP++;
                dP++;
            } else 
                sP++;
        }
        if (dP == d.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.