【动态规划】--最长无重复子串(返回字符串长度vs返回字符串)

leetcode经典题型就是求最长无重复子串,返回值为字符串长度,如果要返回字符串要怎么办呢?一点点往下看就知道了。


原题:

给定一个字符串,找出不含有重复字符的最长子串的长度。
示例:
给定 "abcabcbb" ,没有重复字符的最长子串是 "abc" ,那么长度就是3。
给定 "bbbbb" ,最长的子串就是 "b" ,长度是1。
给定 "pwwkew" ,最长子串是 "wke" ,长度是3。请注意答案必须是一个子串,"pwke" 是 子序列  而不是子串。
(注意:连续才能算子串)


C++

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int size = s.size();
        vector<int> dict(256,-1);
        int maxlen = 0;
        int start = -1;
        for (int i=0;i<size;i++) {
            if (dict[s[i]] > start) {
                start = dict[s[i]];
            }
            dict[s[i]] = i;
            maxlen = max(maxlen, i - start);
        }
        return maxlen;
    }
};

      技巧开辟了一个长度为256的向量,默认值为-1 。以查表的形式统计出现过的字符,出现过的字符会获得i。i - start为子串长度。


Python:

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        ls = list(s)
        res = 0
        substr = []
        for i in range(len(ls)):
            if ls[i] not in substr:
                substr.append(ls[i])
                if res<len(substr):
                    res = len(substr)
            else:
                inx = substr.index(ls[i])
                substr = substr[inx+1:]
                substr.append(ls[i])
        return res

 用python的实现和C++实现不一样,复杂度稍微高一些,不过也能通过leetcode验证。但是,基于python的方法可以稍微改造就求得最长字符串,而不是只返回字符串的长度。改造如下:

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        ls = list(s)
        res = 0
        substr = []
        max_str = ""
        for i in range(len(ls)):
            if ls[i] not in substr:
                substr.append(ls[i])
                if res<len(substr):
                    res = len(substr)
                    max_str = ''.join(substr)
            else:
                inx = substr.index(ls[i])
                substr = substr[inx+1:]
                substr.append(ls[i])
        return max_str

猜你喜欢

转载自blog.csdn.net/leviopku/article/details/82829665