# LeetCode3：Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. 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.

#include <iostream>
#include <string>
#include <cstring>
using namespace std;

/**
Given a string, find the length of the longest substring without repeating characters.
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.
*/
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if(s.empty())
return 0;
int len = s.size();
int bitmap[256] = {0};
//memset(bitmap, 0, sizeof(int) * 26);
int maxLen = 0;
int j = 0;
for(int i = 0; i < len; i++)
{
if(bitmap[s[i]] == 0)
{
bitmap[s[i]] = 1;
}
else
{
maxLen = max(maxLen, i-j);
while(s[i] != s[j])//对bitmap进行设置，将重复元素之前的所有元素对应的位置0，因为这些元素不参与下一次字符串
{
bitmap[s[j]] = 0;
j++;

}
j++;
}
}
maxLen = max(maxLen, len-j);//for循环退出是因为i =len,所以这里还要判断
return maxLen;

}
};

int main(void)
{

string s("wlrbbmqbhcdarzowkkyhiddqscdxrjmowfrxsjybldbefsarcbynecdyggxxpklorellnmpapqfwkhopkmco");
Solution solution;
int res = solution.lengthOfLongestSubstring(s);
cout<<res<<endl;
return 0;
}
-----------------------我和我追猪的梦-----------------------------------------------------------------

posted @ 2014-04-29 12:27  mickole  阅读(583)  评论(0编辑  收藏  举报