Python刷题日记:LeetCode-Longest Substring Without Repeating Characters

来源:互联网 发布:nodejs mysql vue 编辑:程序博客网 时间:2024/06/06 02:41

原题:
Given a string, find the length of the longest substring without repeating characters.

Examples:

Given “abcabcbb”, the answer is “abc”, which the length is 3.

Given “bbbbb”, the answer is “b”, with the length of 1.

Given “pwwkew”, the answer is “wke”, with the length of 3. Note that the answer must be a substring, “pwke” is a subsequence and not a substring.


解题思路:

设置i和j两个指针,通过移动i和j 来寻找最长的子字符串。这里的一个比较关键的点:先设置一个长度为256的[False]*256列表,然后利用字符的ASCII判别字符是否重复出现。具体的细节在拓展知识处。

class Solution(object):    def lengthOfLongestSubstring(self, s):        """        :type s: str        :rtype: int        """        len_string=len(s)        i=0        j=0        maxlen=0        exist=[False]*256        while(j<len_string):            if exist[ord(s[j])]:                maxlen=max(maxlen,j-i)                while(s[i]!=s[j]):                    exist[ord(s[i])]=False                    i=i+1                i=i+1                j=j+1            else:                exist[ord(s[j])]=True                j=j+1        maxlen=max(maxlen,len_string-i)        return maxlen

拓展知识:
要解决上述问题,可以将问题先简化为解决如果确定字符串中的元素是否互不相等。这是解决上述问题的基础。

下面给出四种解决方案:
Solution1:

最简单的解法是将字符串中的每一个字符与剩下的字符比较,如果遇到相同的元素,则返回False,如果直到遍历结束都没有遇到相同元素,则返回True。
这个方案的时间复杂度为O(n*n),空间复杂度为O(1)。当然很明显,这种解法的效率非常低下

def is_unique_char(string):    str_len = len(string)    if str_len > 256:        return False    for pos in xrange(str_len):        for index in xrange(pos+1, str_len):            if string[pos] == string[index]:                return False    return True

这个方案的时间复杂度为O(n*n),空间复杂度为O(1)。当然很明显,这种解法的效率非常低下。

Solution2:
第二种解法是通过构建一个布尔值的数组,索引index表示ASCII码中值为index的字符。将初值置为False,如果某个元素第二次出现设为True,则表示这个字符串出现了重复的字符,函数直接返回。这种解法的Python实现如下:

def is_unique_char(string):    if len(string) > 256:        return False    record = [False] * 256    for ch in string:        ch_val = ord(ch)        if record[ch_val]:            return False        record[ch_val] = True    return True

上面代码的时间复杂度为O(n),空间复杂度为O(1)。

Solution3:
如果使用位运算,结合Python中数字的特殊实现,我们仅需要一个数字来替代record即可实现上面的算法:

def is_unique_char(string):    if len(string) > 256:        return False    record = 0L    for ch in string:        #print record        ch_val = ord(ch)        if (record & (1 << ch_val)) > 0:            return False        record |= (1 << ch_val)    return True
阅读全文
0 0
原创粉丝点击