2 - Longest Substring Without Repeating Characters

来源:互联网 发布:进销存软件哪个好 编辑:程序博客网 时间:2024/05/17 03:32

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) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        vector<int>fre(255,0);        int curLen = 0;        int maxLen = 0;        int length = s.length();        int start = 0;        for(int i = 0; i< length; i++)        {            char ch = s.at(i);            if(fre[ch] == 0)            {                fre[ch] ++;                curLen = i - start + 1;                if(curLen > maxLen)                    maxLen = curLen;            }            else            {                if(curLen>maxLen)                    maxLen = curLen;                char temp = s.at(start);                while(start < i && temp != ch)                {                    fre[ temp ] = 0;                    start++;                    temp = s.at(start);                }                start++;            }        }        return maxLen;    }};


原创粉丝点击