您的位置:首页 > 其它

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

2017-10-02 16:15 330 查看
给定一个字符串,请找出其中无重复字符的最长子字符串。

样例:

例如,在”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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: