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

时间:2017-10-08 17:40:08

标签: python

我想编写一个按字母顺序打印最长子字符串的程序。

如果是tie,它会打印第一个子字符串。

这是我写的

import sys
s1 = str(sys.argv[1])
alpha = "abcdefghijklmnopqrstuvwxyz"

def longest_substring(s1):
    for i in range(len(alpha)):
        for k in range(len(alpha)):
            if alpha[i:k] in s1:
                return alpha[i:k]

print("Longest substring in alphabetical order:", longest_substring(s1))

然而,它不起作用,我不知道如何做第二部分。

请帮帮我吗?

6 个答案:

答案 0 :(得分:0)

以下是您的代码应达到的目的:

private function updateSettings($field, $value)
{
  echo gettype($this->user->settings); // array
  $this->user->settings[$field] = $value;
  $this->updateUser('settings', json_encode($this->user->settings));
  echo gettype($this->user->settings); // string
}

您刚从函数中返回您找到的第一个按字母顺序排列的子字符串。在我的代码中,我们将它们添加到列表中,然后打印出最长的一个。

答案 1 :(得分:0)

您可以构建所有连续子字符串的列表,然后获取具有最大长度的子字符串,而不是构建所有可能的子字符串切片的列表,然后检查字符串中存在哪一个。

通过使用该字符的ord与增加的计数器之间的差异对字符进行分组,可以轻松完成此操作;连续的字符会有一个恒定的差异。 itertools.groupby用于执行分组:

from itertools import groupby, count

alpha = "abcdefghijklmnopqrstuvwxyz"
c = count()

lst_substrs = [''.join(g) for _, g in groupby(alpha, lambda x: ord(x)-next(c))]
substr = max(lst_substrs, key=len)
print(substr)
# abcdefghijklmnopqrstuvwxyz

正如@AdamSmith评论的那样,上面假设字符始终按字母顺序排列。在它们可能不是的情况下,可以通过检查组中的项目是按字母顺序来强制执行订单:

from itertools import groupby, count, tee

lst = []
c = count()
for _, g in groupby(alpha, lambda x: ord(x)-next(c)):
    a, b = tee(g)
    try:
        if ord(next(a)) - ord(next(a)) == -1:
            lst.append(''.join(b)) 
    except StopIteration:
        pass
    lst.extend(b) # add each chr from non-alphabetic iterator (could be empty)

substr = max(lst, key=len) 

答案 2 :(得分:0)

假设子字符串按字母顺序包含2个或更多字符。因此,您不仅应该返回第一个匹配项,而且应该收集全部并找到最长的匹配项。我试着让你的想法保持不变,但这不是最有效的方式:

#include <iostream>
#include <string>
#include <vector>

class A
{
public:

    virtual void whatever() { std::cout << "okay\n"; }
};

class B : public A
{
public:
    float a;
    std::string b;
    int c;

    void print()
    {
        std::cout << "a,b,c values: " << a << ", " << b << ", " << c << std::endl;
    }

    B(void * parameters[])
    {
        this->a = *(static_cast<float*>(parameters[0]));   
        this->b = *(static_cast<std::string*>(parameters[0]));
        this->c = *(static_cast<int*>(parameters[0]));
    }
};

class GameObject
{
public:
    std::vector<A*> components{};

    template<class T>
    void AddComponent(void * parameters[])
    {
        auto t = new T(parameters);
        components.push_back(t);
    }
};

int main()
{
    float f = 2524.218f;
    std::string s = "str";
    int i = 4214;

    auto g = new GameObject;

    void* ptr[3];

    ptr[0] = &f;
    ptr[1] = &s;
    ptr[2] = &i;

    g->AddComponent<B>(ptr);
    static_cast<B*>(g->components[0])->print();
}

答案 3 :(得分:0)

您重新编写warning: No memory at 0x0000000000008000 (vs 0x0000000100000000+0x1000). Nothing written Cannot access memory at address 0x8000 版本以采用二进制比较函数而不是一元函数。

itertools.takewhile

然后你可以小写单词(因为def my_takewhile(predicate, starting_value, iterable): last = starting_value for cur in iterable: if predicate(last, cur): yield cur last = cur else: break 不按字母顺序排列,但任何"Za"在任何[A-Z]之前按字典顺序进行比较并获得所有子字符串。

[a-z]

然后找到i = 0 substrings = [] while i < len(alpha): it = iter(alpha[i:]) substring = str(my_takewhile(lambda x,y: x<y, chr(0), it)) i += len(substring) substrings.append(substring) 中最长的子字符串。

substrings

答案 4 :(得分:0)

备份并再次查看此问题。 1.你正在寻找一个最大值,基本上应该(伪代码):

set a max to ""
loop through sequences
    if new sequence is bigger the max, then replace max
  1. 如果您只是输入一次输入字符,那么找到可以提高效率的序列。
  2. 以下是此版本:

    def longest_substring(s1):
        max_index, max_len = 0, 0 # keep track of the longest sequence here
        last_c = s1[0]  # previous char
        start, seq_len = 0, 1  # tracking current seqence
    
        for i, c in enumerate(s1[1:]):
            if c >= last_c: # can we extend sequence in alpha order
                seq_len += 1
                if seq_len > max_len: # found longer
                    max_index, max_len = start, seq_len
            else: # this char starts new sequence
                seq_len = 0
                start = i + 1
            last_c = c
        return s1[max_index:max_index+max_len]
    

答案 5 :(得分:0)

s = 'azcbobobegghakl'
def max_alpha_subStr(s):
    '''
    INPUT: s, a string of lowercase letters 
    OUTPUT: longest substing of s in which the 
            letters occur in alphabetical order
    '''
    longest = s[0]  # set variables 'longest' and 'current' as 1st letter in s
    current = s[0]
    for i in s[1:]:  # begin iteration from 2nd letter to the end of s
        if i >= current[-1]: # if the 'current' letter is bigger 
                             # than the letter before it 
            current += i     # add that letter to the 'current' letter(s) and 
            if len(current) > len(longest): # check if the 'current' length of
                              # letters are longer than the letters in'longest'
                longest = current # if 'current' is the longest, make 'longest'
                                  # now equal 'current'
        else: # otherwise the current letter is lesser 
              # than the letter before it and 
            current = i # restart evaluating from the point of iteration 
    return print("Longest substring in alphabetical order is: ", longest)
max_alpha_subStr(s)