我正在尝试编写标题所说的代码。如果两个子串的大小相同,只需打印第一个字符串
例如:
s = 'abcbcd'
会打印出来
'abc'
这是我到目前为止所做的:
old_order = ''
re = ''
for r in range(len(s)):
order = ''
for letter in s[r:]:
try:
if letter <= s[s.index(letter)+1]:
order += letter
except:
order += letter
else:
order += letter
print(order)
if r is 0:
old_order = order
if len(order) > len(old_order):
re = order
else:
re = old_order
print(re)
我得到了什么:
aabbcbbc
答案 0 :(得分:0)
def isInAlphabeticalOrder(word):
preString=''
alphaString=''
for char in word:
if(alphaString==''):
alphaString=char
elif(alphaString[-1]<=char):
alphaString+=char
elif(alphaString[-1]>char):
if(len(preString)<len(alphaString)):
preString=alphaString
alphaString=char
else:
alphaString=char
if(len(alphaString)>len(preString)):
preString=alphaString
print(preString)
编辑:详细说明为什么您的代码没有产生正确的结果 - 无论try语句中的结果如何,您都在附上该字母的顺序。因此,如果try语句返回true,则会附加两次字母,否则,附加字母。 编辑:固定代码
答案 1 :(得分:0)
代码:
def longest_sub_str(A):
final_res = ""
tmp = ""
prev = ""
for i in A:
if prev < i:
prev = i
tmp += i
else:
prev = ""
if len(tmp)>len(final_res):
final_res = tmp
tmp = ""
return tmp if len(tmp)>len(final_res) else final_res
print longest_sub_str('abcdddabcddefbcd')
输出:
abcd
答案 2 :(得分:-1)
试试这个(finding the longest substring of letters in alphabetical order in a given string):
s = 'abcbcd'
r = []
substring = []
for length in s:
r = r + [length]
if r == sorted(r) and len(r) >= len(substring):
substring=r
elif r != sorted(r):
r = [r[len(r)-1]]
print(substring)
在我附上的链接中查看 timgeb 的答案以获得完整答案。