leetcode 524. Longest Word in Dictionary through Deleting

257 篇文章 17 订阅

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里的字符和索引放入map中。再对list中的字符串遍历,看看能不能用map中的字符来构成。

package leetcode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

public class Longest_Word_in_Dictionary_through_Deleting_524 {

	public String findLongestWord(String s, List<String> d) {
		HashMap<Character, ArrayList<Integer>> map=new HashMap<Character, ArrayList<Integer>>();
		char[] cs=s.toCharArray();
		for(int i=0;i<cs.length;i++){
			ArrayList<Integer> list=map.getOrDefault(cs[i], new ArrayList<Integer>());
			list.add(i);
			map.put(cs[i], list);
		}
		int maxLength=0;
		ArrayList<String> candidates=new ArrayList<String>();
		for(String string:d){
			int end=-1;
			boolean isOK=true;
			for(int i=0;i<string.length();i++){
				char c=string.charAt(i);
				if(map.get(c)==null){
					isOK=false;
					break;
				}
				ArrayList<Integer> indexes=map.get(c);
				boolean isFind=false;
				for(Integer index:indexes){
					if(index>end){
						isFind=true;
						end=index;
						break;
					}
				}
				if(isFind==false){
					isOK=false;
					break;
				}
			}
			if(isOK==true){
				if(string.length()>maxLength){
					maxLength=string.length();
					candidates.clear();
					candidates.add(string);
				}
				else if(string.length()==maxLength){
					candidates.add(string);
				}
			}
		}
		if(candidates.size()==0){
			return "";
		}
		Collections.sort(candidates);
		return candidates.get(0);
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Longest_Word_in_Dictionary_through_Deleting_524 l=new Longest_Word_in_Dictionary_through_Deleting_524();
		List<String> d=new ArrayList<String>();
		d.add("a");d.add("b");d.add("c");
		System.out.println(l.findLongestWord("abpcplea", d));
	}

}

大神的解法是:先将list中的元素按照 first by length DESC then lexicographical ASC 来排序,之后再遍历list,看list中的元素 p 是否是 s 的子序列。第一个符合的,就是我们要的结果。

public String findLongestWord(String s, List<String> d) {
    if (s.length() == 0 || d.size() == 0) return "";
    
    Collections.sort(d, new Comparator < String > () {
        public int compare(String s1, String s2) {
            return s2.length() != s1.length() ? s2.length() - s1.length() : s1.compareTo(s2);
        }
    });
    
    for (String p : d) {
        if (s.length() < p.length()) continue;
        if (isSubSeq(s, p)) return p;
    }
    
    return "";
}

private boolean isSubSeq(String s, String p) {
    int i = 0, j = 0;
    while (i < s.length() && j < p.length()) {
        if (s.charAt(i) == p.charAt(j)) {
            i++; j++;
        }
        else {
            i++;
        }
    }
    return j == p.length();
}

大神还有不需要使用sort的方法:

因为sorting the dictionary 会带来较大的开销,我们可以跳过sorting,直接来看未排序的dictionary中的元素string xx 是否是 s 的子序列。当这样的一个 xx 符合要求时,我们将xx与其他符合要求的字符串比较 大小和字典序。如此,需要遍历 d 中的所有字符串。

public String findLongestWord(String s, List < String > d) {
    String max_str = "";
    for (String str: d) {
        if (isSubSeq(s, str)) {
            if (str.length() > max_str.length() || (str.length() == max_str.length() && str.compareTo(max_str) < 0))
                max_str = str;
        }
    }
    return max_str;
}

private boolean isSubSeq(String s, String p) {
    int i = 0, j = 0;
    while (i < s.length() && j < p.length()) {
        if (s.charAt(i) == p.charAt(j)) {
            i++; j++;
        }
        else {
            i++;
        }
    }
    return j == p.length();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值