Leetcode-524. Longest Word in Dictionary through Deleting

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。这次比赛略无语,没想到前3题都可以用暴力解。

博客链接:mcf171的博客

——————————————————————————————

Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.

Example 1:

Input:
s = "abpcplea", d = ["ale","apple","monkey","plea"]

Output: 
"apple"

Example 2:

Input:
s = "abpcplea", d = ["a","b","c"]

Output: 
"a"

Note:

  1. All the strings in the input will only contain lower-case letters.
  2. The size of the dictionary won't exceed 1,000.
  3. The length of all the strings in the input won't exceed 1,000.
本来还想着要不要用前缀树什么的,没想到暴力就可以过。。。蛋疼。 Your runtime beats 51.79% of java submissions.

public class Solution {
    public String findLongestWord(String s, List d) {
        Collections.sort(d);
        String result = "";
        for(String item : d){
            if(help(s,item) && item.length() > result.length()) result = item;
        }
        return result;
    }
    private boolean help(String s, String t){
        boolean flag = false;
        int i = 0, j = 0;
        while(i < s.length() && j < t.length()){
            if(s.charAt(i) == t.charAt(j)){
                i++; j++;
            }else i ++;
        }
        if(j == t.length()) flag = true;
        
        return flag;
    }
}




你可能感兴趣的:(算法,java,leetcode,算法)