The longest string of repeated characters python3-free - sliding window algorithm

Title: Given a string, you find out which does not contain a sub-length of the longest string of repeated characters.

Example 1:

Input: "abcabcbb"
Output: 3
Explanation: Because the longest substring of characters without repetition is "abc", so its length is 3.
Example 2:

Example 2:

Input: "bbbbb"
Output: 1
Explanation: Because the longest substring is repeated characters without "b", so that its length is 1.
Example 3:

Example 3:

Input: "pwwkew"
Output: 3
Explanation: Because the longest sub-string is repeated characters without "wke", so its length is 3.
Please note that your answer must be a substring of length, "pwke" is a sub-sequence, not a substring.

Source title

Ideas: the use of a sliding window and begins to view rearwardly from the first character, when the character is repeated to find k, the previous string k (including k) discarding all the characters, and then update maxlen size, until moving to the right.

python code implementation for details attention :( length)

def lengthOfLongestSubstring(s: str) -> int:
    i=1 #当前字符的位置
    begin=0
    maxlen=0
    dropedlen=0#记录舍去的字符串的长度
    if len(s)==0:
        return 0
    if len(s)==1:
        return 1
    for i in range(len(s)):
        if s[i] in s[begin:i]:
            # 先更新maxlen
            templ=len(s[begin:i])
            print("s[i]="+s[i])
            print("字串="+s[begin:i])
            print("templ = "+str(templ))
            maxlen=templ if(templ>maxlen) else maxlen
            # 舍去字串s[begin:i]中s[i]字符及前面的字符
            # 直接用s[begin:i].index(s[i])获得的是相对位置,不是在s中的位置,应该加上dropedlen
            relativelen=s[begin:i].index(s[i])#重复的字符串的相对位置
            begin=relativelen+dropedlen+1
            dropedlen=begin#更新删除的长度
    # 到字符串末再更新一次maxlen
    templ=len(s[begin:i])+1
    maxlen=templ if(templ>maxlen) else maxlen
    return maxlen


s = "au"
print("答案:"+str(lengthOfLongestSubstring(s)))

Guess you like

Origin www.cnblogs.com/zhoujiayingvana/p/12303808.html