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

本文介绍了一种求解字符串中最长无重复字符子串的算法,并提供了详细的Python实现代码。该算法通过双指针技术和ASCII码判断字符重复性,实现了高效查找。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题:
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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值