fast java solution: no sort, one iteration, and seek sequence matching only when necessary


  • 0
    W
    boolean match(char[] sc, char[] dc)
    {        
        int i = 0, j = 0;
        while (i < sc.length && j < dc.length)
        {
            if (sc[i] == dc[j])
                j++;
            i++; 
        }
        return (j == dc.length);
    }
    public String findLongestWord(String s, List<String> d) {
        String res = new String(); 
        char[] sc = s.toCharArray();
        for(String ds: d)
            if ((ds.length() > res.length() || (ds.length() == res.length() && ds.compareTo(res) < 0)) && match(sc, ds.toCharArray()))
                    res = ds; 
         return res;
    }

Log in to reply
 

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