【Leetcode】Longest Substring Without Repeating Characters

来源:互联网 发布:手机淘宝如何申请介入 编辑:程序博客网 时间:2024/06/03 21:52

问题:

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
原创粉丝点击