Longest Substring Without Repeating Characters

来源:互联网 发布:app软件怎么用 编辑:程序博客网 时间:2024/05/30 05:13

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.

题目要求,找出字符串中最长的不包含重复字符串的长度。看到题目的第一想法,是通过双指针,在[low, high]范围内的字符串永远保持没有重复的字符出现,如何判断新加入的字符串是否在[low, high]范围内出现,用到了string自带的find函数,这样可以找到在[low,high]中是否存在新加入的字符,如果存在则返回其下标pos,此时,应该更新low = low + pos + 1;如果不存在,则继续扩大范围。这样可以实现在O(N)的时间复杂度,O(1)的空间复杂度。

class Solution {public:    //双指针 + hashTable    int lengthOfLongestSubstring(string s) {        unsigned sLen = s.size();        if(sLen < 2)            return sLen;        int low = 0, high = 1,max = INT_MIN, pos = -1;        string tmpstr = "";        while(high < sLen)        {            tmpstr = s.substr(low, high - low);            //存在重复元素            if((pos = tmpstr.find(s[high])) != string::npos)            {                low = low + pos + 1;            }            max = (max < (high - low + 1)) ? high - low + 1 : max;            ++high;        }                return max;    }};


0 0