LeetCode 3. Longest Substring Without Repeating Characters

来源:互联网 发布:c语言中switch是什么 编辑:程序博客网 时间:2024/06/08 07:50

题目:https://leetcode.com/problems/longest-substring-without-repeating-characters/#/description

题意:找出字符串中的最长不重复子串的长度。(子串是连续的,而不子序列)。

题解:从前往后扫描这个字符串,用一个数组记录每个字符(最多256个)的当前最靠后的位置,用一个变量记录以当前位置为结尾的不重复子串的起始位置,每次都更新起始位置变为当前字符 s[i] 在之前的字符串 (s[0]-s[i-1]) 中的位置的下一个位置(考虑在之前字符串中不存在的情况,只需将位置数组初始化为-1,即可包含这种情况),然后更新最长长度。这样扫描完之后便能得到最长长度,而且复杂度只有O(N)。

代码:

class Solution {public:    int lengthOfLongestSubstring(string s) {        vector<int> pos(256,-1);        int l,r,max_len=0;        for(l=0,r=0;r<s.size();r++)        {            l=max(l,pos[s[r]]+1);            pos[s[r]]=r;            max_len=max(max_len,r-l+1);        }        return max_len;    }};


0 0