524. Longest Word in Dictionary through Deleting

来源:互联网 发布:excel单元格数据的分列 编辑:程序博客网 时间:2024/05/16 23:43

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.
用双指针匹配s和dic,同时向后扫,碰到相同的,计数加一,当计数等于dic长度的时候,如果比之前的结果长,或者跟之前结果一样长且首字母更小,就替换掉。代码如下:

public class Solution {    public String findLongestWord(String s, List<String> d) {        String res = "";        char[] ch  = s.toCharArray();        for (String str: d) {            int i = 0, j = 0;            char[] dic = str.toCharArray();            while (i < ch.length && j < dic.length) {                if (ch[i] == dic[j]) {                    i ++;                    j ++;                } else {                    i ++;                }                if (j == dic.length) {                    if (j > res.length() || (j == res.length() && res.charAt(0) > dic[0])) {                        res = str;                    }                }            }        }        return res;    }}

0 0
原创粉丝点击