LeetCode - Longest Substring Without Repeating Characters

来源:互联网 发布:日本妹子发型 知乎 编辑:程序博客网 时间:2024/04/29 06:20



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) {        const int N=256;int max=0,len=0,start=0;vector<int> matrix(N,-1);for(int i=0;i<s.size();i++){if(matrix[s[i]]==-1||matrix[s[i]]<start){len++;}else{start=matrix[s[i]]+1;max=max>len?max:len;len=i-matrix[s[i]];}matrix[s[i]]=i;}return max>len?max:len;    }};