[Leetcode3]无重复字符的最长子串

给定一个字符串,找出不含有重复字符的最长子串的长度。

用了比较暴力的解法,用一个指针向前移动,另一个指针在左侧部分检测非重复字符,复杂度应该是:O(n^2

python:

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        lenstr = len(s)
        if lenstr <= 1:
            return lenstr
        maxstr = 0
        left = 0
        count = 0
        for i in range(1,lenstr):
            j=i-1
            while j>=left:
                if s[j] != s[i]:
                    count = i-j+1
                    j -= 1
                else:
                    count = i-j
                    left = j+1
                    break
            if count>maxstr:
                maxstr = count
                
        return maxstr

C++: 

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int lenstr = s.length();
        int maxstr = 0;
        int left = 0;
        int count = 0;
        if (lenstr < 2){
            maxstr = lenstr;
        }
        for(int i=1;i<lenstr;i++){
            int j = i-1;
            while(j>=left){
                if(s[j] != s[i]){
                    count = i-j + 1;
                    j -= 1;
                }
                else{
                    count = i-j;
                    left = j + 1;
                    break;
                }
            }
            if(count>maxstr){
                maxstr = count;
            }
        }
        return maxstr;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_40501689/article/details/82756732