LeetCode Problems #3

2018年9月9日

#3. Longest Substring Without Repeating Characters

问题描述:

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

样例:

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.

问题分析:

本题难度为Medium!已给出的函数定义为:

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """

其中s为字符串,返回值应为一个整数。

本题直接遍历字符串,寻找最长子字符串,并返回其长度;算法(伪代码)如下:

判断字符串s是否为空字符串,若是,则返回0
初始化最长子字符串长度longest为1
遍历字符串s直到倒数第二个字符,循环的字符下标为i
    初始化临时子字符串substr为当前字符s[i]
    从字符串s的i+1遍历到字符串s尾,循环的字符下标为j
        判断字符s[j]是否在substr中已存在,若是则break退出循环,否则将s[j]添加到substr
    判断substr的长度是否比longest的值大,若是,则更新longest的值为substr的字符串长度
返回longest

代码实现如下:

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        if s=="":
            return 0
        longest=1
        for i in range(len(s)-1):
            substr=s[i]
            for j in range(i+1, len(s)):
                if s[j] in substr:
                    break
                else:
                    substr+=s[j]
            if len(substr)>longest:
                longest=len(substr)
        return longest

猜你喜欢

转载自blog.csdn.net/qq_38789531/article/details/82561378
今日推荐