按字母顺序查找最长的子字符串

时间:2013-10-26 01:43:03

标签: python

我在另一个主题上找到了这个代码,但它按连续字符排序子字符串,而不是按字母顺序排序。如何按字母顺序更正?它打印出lk,我想要打印ccl。感谢

ps:我是python的初学者

s = 'cyqfjhcclkbxpbojgkar'
from itertools import count

def long_alphabet(input_string):
    maxsubstr = input_string[0:0] # empty slice (to accept subclasses of str)
    for start in range(len(input_string)): # O(n)
        for end in count(start + len(maxsubstr) + 1): # O(m)
            substr = input_string[start:end] # O(m)
            if len(set(substr)) != (end - start): # found duplicates or EOS
                break
            if (ord(max(sorted(substr))) - ord(min(sorted(substr))) + 1) == len(substr):
                maxsubstr = substr
    return maxsubstr

bla = (long_alphabet(s))
print "Longest substring in alphabetical order is: %s" %bla

19 个答案:

答案 0 :(得分:14)

s = 'cyqfjhcclkbxpbojgkar'
r = ''
c = ''
for char in s:
    if (c == ''):
        c = char
    elif (c[-1] <= char):
        c += char
    elif (c[-1] > char):
        if (len(r) < len(c)):
            r = c
            c = char
        else:
            c = char
if (len(c) > len(r)):
    r = c
print(r)

答案 1 :(得分:5)

尝试更改此内容:

        if len(set(substr)) != (end - start): # found duplicates or EOS
            break
        if (ord(max(sorted(substr))) - ord(min(sorted(substr))) + 1) == len(substr):

到此:

        if len(substr) != (end - start): # found duplicates or EOS
            break
        if sorted(substr) == list(substr):

这将为您的示例输入字符串显示ccl。代码更简单,因为您正试图解决一个更简单的问题: - )

答案 2 :(得分:2)

您可以通过注意字符串可以分解为最大长度的有序子字符串的运行来改进算法。任何有序的子字符串必须包含在其中一个

这允许您只通过字符串O(n)

迭代一次
def longest_substring(string):
    curr, subs = '', ''
    for char in string:
        if not curr or char >= curr[-1]:
            curr += char
        else:
            curr, subs = '', max(curr, subs, key=len)
    return max(curr, subs, key=len)

答案 3 :(得分:2)

以递归方式,您可以从 itertools

中导入计数

或定义相同的方法:

def loops( I=0, S=1 ):
    n = I
    while True:
        yield n
        n += S

使用此方法,您可以在anallitic流程中创建任何子字符串时获取端点的值。

现在查看anallize方法(基于 spacegame 问题和Mr. Tim Petters 建议)

def anallize(inStr):
    # empty slice (maxStr) to implement
    # str native methods
    # in the anallize search execution
    maxStr = inStr[0:0]
    # loop to read the input string (inStr)
    for i in range(len(inStr)):
        # loop to sort and compare each new substring
        # the loop uses the loops method of past
        # I = sum of: 
        #     (i) current read index
        #     (len(maxStr)) current answer length
        #     and 1
        for o in loops(i + len(maxStr) + 1):
            # create a new substring (newStr)
            # the substring is taked:
            # from: index of read loop (i)
            # to:   index of sort and compare loop (o)
            newStr = inStr[i:o]

            if len(newStr) != (o - i):# detect and found duplicates
                break
            if sorted(newStr) == list(newStr):# compares if sorted string is equal to listed string
                # if success, the substring of sort and compare is assigned as answer
                maxStr = newStr
    # return the string recovered as longest substring
    return maxStr

最后,对于测试或执行pourposes:

# for execution pourposes of the exercise:
s = "azcbobobegghakl"
print "Longest substring in alphabetical order is: " + anallize( s )

这项工作的重点是: spacegame 并由 Tim Petters 先生参加,正在使用本地str方法和代码的可重用性。

答案是:

按字母顺序排列的最长子字符串为: ccl

答案 4 :(得分:1)

N

答案 5 :(得分:1)

使用list和max函数大幅减少代码。

actual_string = 'azcbobobegghakl'
strlist = []
i = 0
while i < len(actual_string)-1:
    substr = ''
    while actial_string[i + 1] > actual_string[i] :
        substr += actual_string[i]
        i += 1
        if i > len(actual_string)-2:
            break
    substr += actual-string[i]
    i += 1
    strlist.append(subst)
print(max(strlist, key=len))

答案 6 :(得分:1)

在Python中,与必须比较ASCII值的java脚本相比,字符比较很容易。根据python

a&gt; b给出布尔值False,b&gt; a给出布尔值True

使用此按字母顺序的最长子字符串可以使用以下算法找到:

def comp(a,b):
    if a<=b:
        return True
    else:
        return False
s = raw_input("Enter the required sting: ")
final = []
nIndex = 0
temp = []
for i in range(nIndex, len(s)-1):
    res = comp(s[i], s[i+1])
    if res == True:       
           if temp == []:
           #print i
               temp.append(s[i])
               temp.append(s[i+1])
           else:
               temp.append(s[i+1])
       final.append(temp)
        else:
       if temp == []:
        #print i
        temp.append(s[i])
       final.append(temp)
       temp = []
lengths = []
for el in final:
    lengths.append(len(el))
print lengths
print final
lngStr = ''.join(final[lengths.index(max(lengths))])
print "Longest substring in alphabetical order is: " + lngStr

答案 7 :(得分:0)

s = "azcbobobegghakl"
ls = ""
for i in range(0, len(s)-1):
    b = ""
    ss = ""
    j = 2
    while j < len(s):
        ss = s[i:i+j]
        b = sorted(ss)
        str1 = ''.join(b)
        j += 1
        if str1 == ss:
            ks = ss
        else:
            break
    if len(ks) > len(ls):
        ls = ks
print("The Longest substring in alphabetical order is "+ls)

答案 8 :(得分:0)

稍微不同的实现,按字母顺序构建所有子串的列表并返回最长的子串:

def longest_substring(s):
    in_orders = ['' for i in range(len(s))]
    index = 0
    for i in range(len(s)):
        if (i == len(s) - 1 and s[i] >= s[i - 1]) or s[i] <= s[i + 1]:
            in_orders[index] += s[i]
        else:
            in_orders[index] += s[i]
            index += 1
    return max(in_orders, key=len)  

答案 9 :(得分:0)

这对我有用

s = 'cyqfjhcclkbxpbojgkar'

lstring = s[0]
slen = 1

for i in range(len(s)):
    for j in range(i,len(s)-1):
            if s[j+1] >= s[j]:
                    if (j+1)-i+1 > slen:
                        lstring = s[i:(j+1)+1]
                        slen = (j+1)-i+1
            else:
                        break

print("Longest substring in alphabetical order is: " + lstring)

输出:按字母顺序排列的最长子字符串为:ccl

答案 10 :(得分:0)

input_str = "cyqfjhcclkbxpbojgkar"
length = len(input_str) # length of the input string
iter = 0
result_str = '' # contains latest processed sub string
longest = '' # contains longest sub string alphabetic order 
while length > 1: # loop till all char processed from string
    count = 1
    key = input_str[iter] #set last checked char as key 
    result_str += key # start of the new sub string
    for i in range(iter+1, len(input_str)): # discard processed char to set new range
      length -= 1
      if(key <= input_str[i]): # check the char is in alphabetic order 
        key = input_str[i]
        result_str += key # concatenate the char to result_str
        count += 1
      else:
        if(len(longest) < len(result_str)): # check result and longest str length
          longest = result_str # if yes set longest to result
        result_str = '' # re initiate result_str for new sub string
        iter += count # update iter value to point the index of last processed char
        break

    if length is 1: # check for the last iteration of while loop
        if(len(longest) < len(result_str)):
          longest = result_str

print(longest);

答案 11 :(得分:0)

哇,这里有一些令人印象深刻的代码片段...... 我想添加我的解决方案,因为我认为它很干净:

public

答案 12 :(得分:0)

不使用库,而是使用函数ord(),该函数返回字符的ascii值。 假设:输入将使用小写字母,并且不使用特殊字符

s = 'azcbobobegghakl'

longest = ''

for i in range(len(s)):
    temp_longest=s[i]

    for j in range(i+1,len(s)):

        if ord(s[i])<=ord(s[j]):
            temp_longest+=s[j]
            i+=1
        else:
            break

    if len(temp_longest)>len(longest):
        longest = temp_longest

print(longest)

答案 13 :(得分:0)

在Python中按字母顺序查找最长的子字符串

在python shell 'a' < 'b' or 'a' <= 'a' is True

result = ''
temp = ''
for char in s:
    if (not temp or temp[-1] <= char):
        temp += char
    elif (temp[-1] > char):
        if (len(result) < len(temp)):
            result = temp
        temp = char

if (len(temp) > len(result)):
    result = temp

print('Longest substring in alphabetical order is:', result)

答案 14 :(得分:0)

s=input()
temp=s[0]
output=s[0]
for i in range(len(s)-1):
    if s[i]<=s[i+1]:
        temp=temp+s[i+1]
        if len(temp)>len(output):
            output=temp           
    else:
        temp=s[i+1]

print('Longest substring in alphabetic order is:' + output)

答案 15 :(得分:0)

我对在线EDX上的一项测试有类似的疑问。花了20分钟进行头脑风暴,找不到解决方案。但是答案就传给了我。这很简单。使我无法接受其他解决方案的原因-光标不应停止或具有唯一值,也就是说如果我们有edx字符串s ='azcbobobegghakl',则应输出-'beggh'而不是'begh'(唯一集)或'kl '(按照与字母字符串相同的最长长度)。这是我的答案,它有效

n=0
for i in range(1,len(s)):
    if s[n:i]==''.join(sorted(s[n:i])):
        longest_try=s[n:i]
    else:
        n+=1

答案 16 :(得分:0)

在某些情况下,输入是混合字符,例如“Hello”或“HelloWorld”

**条件 1:**确定顺序不区分大小写,即字符串“Ab”被视为按字母顺序排列。

**条件 2:**您可以假设输入不会有一个字符串,其中按字母顺序排列的可能连续子字符串的数量为 0。即输入不会有像“zxec”这样的字符串。< /p>

   string ="HelloWorld"
    s=string.lower()
    r = ''
    c = ''
    last=''
    for char in s:
        if (c == ''):
            c = char
        elif (c[-1] <= char):
            c += char
        elif (c[-1] > char):
            if (len(r) < len(c)):
                r = c
                c = char
            else:
                c = char
    if (len(c) > len(r)):
        r = c
    for i in r:
        if i in string:
            last=last+i
        else:
            last=last+i.upper()
    if len(r)==1:
        print(0)
    else:
        print(last)

出:黄色

答案 17 :(得分:0)

```python
s = "cyqfjhcclkbxpbojgkar"  # change this to any word
word, temp = "", s[0]  # temp = s[0] for fence post problem
for i in range(1, len(s)):  # starting from 1 not zero because we already add first char
    x = temp[-1]  # last word in var temp
    y = s[i]  # index in for-loop
    if x <= y:
        temp += s[i]
    elif x > y:
        if len(temp) > len(word):  #storing longest substring so we can use temp for make another substring
            word = temp
        temp = s[i]  #reseting var temp with last char in loop
    if len(temp) > len(word):
        word = temp
print("Longest substring in alphabetical order is:", word)
```

我的代码将当前最长的子字符串存储在变量 temp 中,然后将 for 循环中的每个字符串索引与 temp (temp[-1]) 中的最后一个字符进行比较,如果索引高于或与 (temp[-1]) 相同,则从临时索引中添加该字符。如果索引低于 (temp[-1]) 检查变量 word 和 temp 哪个具有最长的子字符串,在重置变量 temp 之后,我们可以创建另一个子字符串,直到字符串中的最后一个字符。

答案 18 :(得分:-2)

另一种方式:

s = input("Please enter a sentence: ")
count = 0
maxcount = 0
result = 0
for char in range(len(s)-1):
    if(s[char]<=s[char+1]):
       count += 1        
    if(count > maxcount):
           maxcount = count
           result = char + 1

    else:

        count = 0
startposition = result - maxcount
print("Longest substring in alphabetical order is: ", s[startposition:result+1])