【Leetcode】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.

代码:

//
//  lssworc.cpp
//  Test
//
//  Created by mac on 5/19/14.
//  Copyright (c) 2014 mac. All rights reserved.
//

#include "lssworc.h"
#include <iostream>
#include <stdlib.h>
#include <string.h>

using namespace std;

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int cache[256];
        memset(cache , 0 , sizeof(cache));
        
        int maxR = 0;
        int temp = 0;
        int start = 0;
        for (int i = 0 ,start = 0; i < s.length() && start < s.length(); i++) {
            int size = s[i];
            temp ++;
            if(++cache[size] > 1)
            {
                maxR = max(maxR , temp-1);
                do {
                    int haha = s[start];
                    cache[haha] --;
                    temp --;
                    if(s[start] == s[i])
                    {
                        cout<<s[start]<<endl;
                        start ++;
                        cout<<temp<<endl;
                        break;
                    }
                    start ++;
                    
                }while(1);
            }
            
            
        }
        maxR = max(maxR , temp-1);
        
        return maxR;
    }
};

int main()
{
    Solution s;
    cout<<s.lengthOfLongestSubstring(string("wlrbbmqbhcdarzowkkyhiddqscdxrjmowfrxsjybldbefsarcbynecdyggxxpklorellnmpapqfwkhopkmco"))<<endl;
}

分析:

原理很简单:

1. 因为一个字符只有一个字节,所以最大值是 255,基于这一点,设置一个 256 的cache,来统计所有的字符出现的次数,如果次数大于1,则出现的是第二次了。

2. 基于第一点,从新的字符串开始找到重复的那个字符,并缩减到最大字串,从重复的下一个开始重新统计。


总结:

这个还是比较有成就感,自己想出来的解法。只能说明字符串功底还行。再接再厉。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值