您的位置:首页 > 其它

lintcode:Longest Substring Without Repeating Characters

2015-05-17 17:55 288 查看
Given a string, find the length of the longest substring without repeating characters.

Example

For example, the longest substring without repeating letters for
"abcabcbb"
is
"abc"
,
which the length is
3
.
For
"bbbbb"
the
longest substring is
"b"
, with the length of
1
.

Challenge

O(n) time

class Solution {
public:
/**
* @param s: a string
* @return: an integer
*/
int lengthOfLongestSubstring(string s) {
// write your code here
vector<int> dp(s.size()+1);
map<int, int> posMap;

dp[0] = 0;
int retMax = 0;

for (int i=0; i<s.size(); i++)
{
if (posMap.count(s.at(i)) == 0)
{
dp[i+1] = dp[i]+1;
}
else
{
dp[i+1] = min(i-posMap[s.at(i)], dp[i]+1);
}

posMap[s.at(i)] = i;

retMax = max(retMax, dp[i+1]);
}

return retMax;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: