題目描述:
給定一個(gè)字符串和一個(gè)字符串字典,找到字典里面最長(zhǎng)的字符串,該字符串可以通過刪除給定字符串的某些字符來得到。如果答案不止一個(gè),返回長(zhǎng)度最長(zhǎng)且字典順序最小的字符串。如果答案不存在,則返回空字符串。
示例1:
輸入:
s = "abpcplea", d = ["ale","apple","monkey","plea"]
輸出:
"apple"
示例2:
輸入:
s = "abpcplea", d = ["a","b","c"]
輸出:
"a"
說明:
所有輸入的字符串只包含小寫字母。
字典的大小不會(huì)超過 1000。
所有輸入的字符串長(zhǎng)度不會(huì)超過 1000。
解答思路一:按順序進(jìn)行索引,切片,找到匹配的字符串
class Solution(object):
def findLongestWord(self, s, d):
"""
:type s: str
:type d: List[str]
:rtype: str
"""
max = float('-inf')
result = ''
source = s
for string in d:
i = 0
while i < len(string):
if string[i] in s:
try:
s = s[s.index(string[i])+1:]
except IndexError:
s = ''
finally:
i += 1
else:
break
if i == len(string):
if len(string) > max:
max = len(string)
result = string
elif len(string) == max:
result = result if result < string else string
else:
pass
s = source
return result
解答思路二:排序,然后找到匹配值
class Solution(object):
def findLongestWord(self, s, d):
"""
:type s: str
:type d: List[str]
:rtype: str
"""
# 先將d中的單詞按照長(zhǎng)度由長(zhǎng)到短排序,再按照字母順序,從小到大
d.sort(key=lambda x: (-len(x), x))
# 然后依次比較d中字符串與字典s,如果出現(xiàn)匹配就直接返回
for word in d:
i = 0
for l in s:
if l == word[i]:
i += 1
if i == len(word):
return word
return ''