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

SouthEast

利用两指针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;
}

转载于:https://www.cnblogs.com/mickole/p/3698956.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值