Java solution


  • 0
    S
        public String findLongestWord(String s, List<String> d) {
            Collections.sort(d);
            int longest = 0, len = s.length();
            int len1;
            String ans = "";
            for (String str : d) {
                len1 = str.length();
                if (len1 <= longest || len1 > len)
                    continue;
                if (canForm(s, str)) {
                    longest = len1;
                    ans = str;
                }
            }
            return ans;
        }
        
        public boolean canForm (String input, String part) {
            int p1 = 0, p2 = 0;
            int len1 = input.length(), len2 = part.length();
            
            while (p1 < len1 && p2 < len2) {
                while (p1 < len1 && input.charAt(p1) != part.charAt(p2))
                    p1++;
                if (p1 < len1)
                    p2++;
                p1++;
            }
            if (p2 == len2)
                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.