Longest Word in Dictionary through Deleting
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.
时间复杂度:O(M * N)
空间复杂度:O(1)
需要保证两个等长的符合条件的str中,取字典序最小的。也可以先对List中的元素排序(可能性能更好)
public String findLongestWord(String s, List<String> d) {
int stringLen = s.length();
int listLen = d.size();
if(stringLen == 0 || listLen == 0)
return "";
String result = "";
char[] charArray = s.toCharArray();
int maxLen = 0;
for(String str : d){
int length = str.length();
int i = 0;
int j = 0;
int count = 0;
while(i < stringLen && j < length){
if(charArray[i] == str.charAt(j)){
i++;
j++;
count++;
}else{
i++;
}
}
if(j == length){
if(count > maxLen){
maxLen = count;
result = str;
}else if(count == maxLen){
if(result == ""){
result = str;
}else if(!result.equals(str)){
result = getSmallestLex(result,str);
}
}
}
}
return result;
}
public String getSmallestLex(String A,String B){
int length = A.length();
int i = 0;
int j = 0;
while(i < length){
if(A.charAt(i) < B.charAt(j)){
return A;
}else if(A.charAt(i) > B.charAt(j)){
return B;
}else{
i++;
j++;
}
}
return A;
}