前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发优快云,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:
- All the strings in the input will only contain lower-case letters.
- The size of the dictionary won't exceed 1,000.
- The length of all the strings in the input won't exceed 1,000.
public class Solution {
public String findLongestWord(String s, List<String> 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;
}
}
本文介绍了一个利用简单暴力方法解决字符串匹配问题的算法,并通过实例展示了如何从给定字符串中找出字典中最长的可匹配子序列。该方法首先对字典进行排序,然后逐一检查每个词是否为给定字符串的有效子序列。
315

被折叠的 条评论
为什么被折叠?



