前几天在华为OD一面中遇到了这个问题,最长连续子字符串。
def find_longest_increasing_substring(string):
"""
最长递增子串
eg. ababdddd ---> abd
:param string:
:return:
"""
if not string:
return ""
result = ""
cur_result = ""
for char in string:
if cur_result:
if ord(char) > ord(cur_result[-1]):
cur_result += char
else:
if len(cur_result) > len(result):
result = cur_result
cur_result = ""
if not cur_result:
cur_result += char
return result
下面扩展几个类似的题
最长重复子串
def find_longest_repeated_substring(string):
"""
最长重复子串
:param string:
:return:
"""
if not string:
return ""
longest = ""
current_char = ""
for char in string:
if current_char:
if current_char[-1] == char:
current_char += char
else:
if len(current_char) > len(longest):
longest = current_char
current_char = ""
if not current_char:
current_char = char
return longest
最长连续子串
def find_longest_continuously_increasing_substring(string):
"""
最长连续递增子串
:param string:
:return:
"""
if not string:
return ""
result = ""
cur_result = ""
for char in string:
if cur_result:
if ord(char) == ord(cur_result[-1]) + 1:
cur_result += char
else:
if len(cur_result) > len(result):
result = cur_result
cur_result = ""
if not cur_result:
cur_result += char
return result
总结:
思路都是大同小异。用两个变量分别保存最长子串和当前符合要求子串。遍历字符串,检查一遍即可。
将字符串转化为ascii的方法可能会忘记:ord(字符串)
相应的,ascii码转化为python字符串的方法:chr(范围内的整形)