最长无重复字符的子串

来源:互联网 发布:网络监控软件破解版 编辑:程序博客网 时间:2024/05/18 02:53

题目

给定一个字符串,请找出其中无重复字符的最长子字符串。

样例
例如,在”abcabcbb”中,其无重复字符的最长子字符串是”abc”,其长度为 3。

对于,”bbbbb”,其无重复字符的最长子字符串为”b”,长度为1。

思想

动态规划加哈希,
重点当hash[s[i]]存在时,根据hash[s[i]]的值是否大于start做两种不同的处理

class Solution {public:    /**     * @param s: a string     * @return: an integer      */    int lengthOfLongestSubstring(string s) {        // write your code here        unordered_map<char,int> map;        int start = 0;        int maxlen = -1;        int i = 0, len = s.size();        while(i<len){            if(!map.count(s[i])){                map[s[i]] = i;            }            else{                //如果map[s[i]]<start,那么需要更新hash的值,而不是当做有重复值去计算字符串长度                if(map[s[i]] < start) map[s[i]] = i;                else{                    if(maxlen<i-start) maxlen = i-start;                    start = map[s[i]]+1;                    map[s[i]] = i;                }            }            i++;        }        if(maxlen<i-start) maxlen = i-start;        return maxlen;    }};
0 0