最长无重复字符的子串-LintCode

来源:互联网 发布:80端口入侵教程 编辑:程序博客网 时间:2024/05/17 13:40

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

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

挑战 :
O(n) 时间

思路:
遍历字符串,对于每个字符计算长度和起始位置,若在已遍历的字符串中不存在,则起始位置不变,直接计算长度;若在已遍历的字符串中存在,更新起始位置,计算长度,最终取最大长度。

#ifndef C384_H#define C384_H#include<iostream>#include<vector>#include<map>using namespace std;class Solution {public:    /*    * @param s: a string    * @return: an integer    */    int lengthOfLongestSubstring(string &s) {        // write your code here        if (s.empty())            return 0;        int res = 0;        int start = 0;        map<char, int> m;        for (int i = 0; i < s.size();++i)        {            if (m.find(s[i]) == m.end())            {                m[s[i]] = i;            }            else            {                start = maxVal(m.find(s[i])->second+1,start);                   m.find(s[i])->second = i;            }            res = maxVal(res, i - start + 1);        }        return res;    }    int maxVal(int a, int b)    {        return a > b ? a : b;    }};#endif
原创粉丝点击