解题思想:首先先遍历数据获得可能的答案,再对答案进行遍历选择出长度最长的且字母序最小的字符串
class Solution(object):
def findLongestWord(self, s, dictionary):
"""
:type s: str
:type dictionary: List[str]
:rtype: str
"""
answer = []
for i in range(len(dictionary)):
j = 0
k = 0
while j<len(s) and k<len(dictionary[i]):
if s[j] == dictionary[i][k]:
j +=1
k +=1
else:
j +=1
if k == len(dictionary[i]):
answer.append(dictionary[i])
maxlen = 0
result = ''
for i in range(len(answer)):
if len(answer[i]) > maxlen:
result = answer[i]
maxlen = len(answer[i])
elif len(answer[i]) == maxlen:
for char1, char2 in zip(answer[i], result):
if char1 < char2:
result = answer[i]
break
elif char1 > char2:
break
return result
class Solution {
public:
string findLongestWord(string s, vector<string>& dictionary) {
std::vector<std::string> answer;
for (const auto& word : dictionary) {
int j = 0, k = 0;
while (j < s.length() && k < word.length()) {
if (s[j] == word[k]) {
j++;
k++;
} else {
j++;
}
}
if (k == word.length()) {
answer.push_back(word);
}
}
int maxlen = 0;
std::string result = "";
for (const auto& word : answer) {
if (word.length() > maxlen) {
result = word;
maxlen = word.length();
} else if (word.length() == maxlen) {
for (int i = 0; i < word.length(); ++i) {
if (word[i] < result[i]) {
result = word;
break;
} else if (word[i] > result[i]) {
break;
}
}
}
}
return result;
}
};