2016-09-16 9 views
1

文字のアルファベット順の最長部分文字列を返す関数を記述しようとしています。たとえば、s = 'azcbobobegghakl'の場合、関数は 'beggh'を返します。アルファベット順に最長のアルファベット順の部分文字列を取得するには

これは私の関数ですが、まだ完全ではありませんが、サブのリストは返されません。

"IndexError: string index out of range"

def longest_substring(s): 
    sub=[] 
    for i in range (len(s)-1): 
     subs=s[i] 
     counter=i+1 
     while ord(s[i])<ord(s[counter]): 
      subs+=s[counter] 
      counter+=1 
     sub.append(subs) 
    return sub 
+0

counter'は 'LEN(複数可)を' '超えますか? 'while'ループであなたのケースがこの入力で失敗すると思います:' acdb'残りの文字をすべて第1文字 'a'と比較しようとしているので、' acdb'として答えが間違っています。 'acd'と思う.. –

+1

https://en.wikipedia.org/wiki/Longest_increasing_subsequence –

+0

@ cricket_007実際にはそうではない...サブシーケンスは要素をスキップすることができます! – wim

答えて

3

それは最適ではありません(線形時間O(n)で動作します)しかし、私は(Pythonの3)あなたのコードにいくつかの変更をした: リターンエラーがある

def longest_substring(s): 
    length = len(s) 
    if length == 0 :   # Empty string 
     return s 
    final = s[0] 
    for i in range (length-1): 
     current = s[i] 
     counter = i+1 
     while counter < length and ord(s[i]) <= ord(s[counter]): 
      current += s[counter] 
      counter +=1 
      i+=1 
     if len(final) < len(current): 
      final = current 
    return final 
s = 'azcbobobegghakl' 
print(longest_substring(s)) 

出力:

beggh 

Modifications:

  • You are comparing character with fixed position i.e. in while loop you are incrementing only counter not i so I incremented the ith position also.(So we avoid checking the characters which are already checked, So it does this in linear time O(n) I think..)
  • Also you are only checking less than for condition while ord(s[i])<ord(s[counter]): But you also have to check for equals too.
  • You created one list where you append every sequence which is unnecessary unless you want do any other calculations on the sequence, So I take string and if previous sequence's length is small then I updated it with new sequence.

注: 2つの配列の長さが同じ場合は、最初に出現した配列が出力として表示されます。

別の入力:

s = 'acdb' 

出力:

acd 

私は、これはあなたを助けることを願っています。

+0

ありがとうございます@Kalpesh –

+0

あなたのコードのこの部分は何ですか?:len(sub)

+0

@ A.E。現在のシーケンスの長さが以前の最大のシーケンスよりも大きければ、それを答えに割り当てます。 –

0

これはかなり単純O(n)を行うことができる。

def gen(s): 
    prev = '' 
    for c in s: 
     if c >= prev[-1:]: 
      prev += c 
     else: 
      yield prev 
      prev = c 
    if prev: 
     yield prev 

print(max(gen('azcbobobegghakl'), key=len))