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.

解题思路:

一开始,没看清题目要求,以为是去重,一提交出错才知不是。

只要谈到去重或者无重复之类的词,就应该想到哈希表或bitmap。

这里直接引用网上大牛的解题方法:http://blog.csdn.net/kenden23/article/details/16839757

利用两指针i,j。i走在前,每次到哈希表中查找之前是否出现,没有则将对应位置置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  阅读(609)  评论(0编辑  收藏  举报