zl程序教程

您现在的位置是:首页 >  其它

当前栏目

通过删除字母匹配到字典里最长单词

删除 通过 匹配 字典 最长 单词 字母
2023-09-14 09:01:28 时间

524. 通过删除字母匹配到字典里最长单词

给你一个字符串 s 和一个字符串数组 dictionary ,找出并返回 dictionary 中最长的字符串,该字符串可以通过删除 s 中的某些字符得到。
如果答案不止一个,返回长度最长且字母序最小的字符串。如果答案不存在,则返回空字符串。

示例 1:

输入:s = “abpcplea”, dictionary = [“ale”,“apple”,“monkey”,“plea”]
输出:“apple”

示例 2:

输入:s = “abpcplea”, dictionary = [“a”,“b”,“c”]
输出:“a”

代码(java):

import java.util.Arrays;
import java.util.List;

public class longestWord {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		String s = "abpcplea";
		String [] q = {"ale","apple","monkey","plea"};
		List<String> dictionary = Arrays.asList(q) ;
		
		String s1 = findLongestWord(s, dictionary);
		System.out.println(s1);
	}
	 public static String findLongestWord(String s, List<String> d) {
		 String longestWord = "";
		 for(String target : d) {
			 int l1 = longestWord.length(), l2 = target.length();
			 if(l1 > l2 || (l1 == l2 && longestWord.compareTo(target)<0)) {
				 continue;
			 }
			 if(isSubstr(s, target)) {
				 longestWord = target;
			 }
		 }
		 
		 return longestWord;
	 }
	 
	 private static boolean isSubstr(String s, String target) {
		 int i = 0, j = 0;
		 while(i < s.length() && j < target.length()) {
			 if(s.charAt(i) == target.charAt(j)) {
				 j++;
			 }
			 i++;
		 }
		 return j == target.length();
	 }
}

复杂度分析:

  • 时间复杂度:O(d×(m+n)),其中 d表示dictionary 的长度,m 表示 s的长度,n 表示 dictionary 中字符串的平均长度。我们需要遍历dictionary 中的 d 个字符串,每个字符串需要O(n+m) 的时间复杂度来判断该字符串是否为 s 的子序列。

  • 空间复杂度:O(1)。

提示:

  • 1 <= s.length <= 1000
  • 1 <= dictionary.length <= 1000
  • 1 <= dictionary[i].length <= 1000
  • s 和 dictionary[i] 仅由小写英文字母组成

来源:力扣(LeetCode)

注:仅供学习参考!