leetcode 3. Longest Substring Without Repeating Characters

来源:互联网 发布:sql优化书籍推荐 编辑:程序博客网 时间:2024/06/08 03:07

3. Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring"pwke" is a subsequenceand not a substring.

way-1: 还是有一点两根指针的感觉,后面后移,找到重复的就前面的指针重新确定起始点。


way-2:用map,遍历s每一位 map[s[i]]存的是s[i]的下标,
如果找到重复的,就统计map长度,然后把begin到map[s[i]]的位全部清理出map。从map[s[i]] + 1 重新开始。
如果没有,就加入map

第一种的速度比较快!


class Solution {public:    int lengthOfLongestSubstring(string s)     {        //way-1        if(s == "")            return 0;        int j = 0; //后面的指针        int ret = 1;        for (int is = 0; is < s.length() - 1; is++) //is是前面的指针        {               j++;            string m1 = s.substr(is, j - is);            while (m1.find(s[j]) == -1 && j < s.length())            {                m1 = m1 + s[j];                j ++;            }                        ret = max(ret, j - is);            if(j < s.length())              {                     is = is + m1.find(s[j]); //m1.find(s[j])是 m1 中s[j]在的位数,m1是从is开始的.重新定位下一次开始的地点            }        }        return ret;                        //way-2        /*        map<char,int> s_count;        int maxlength = 0;        int begin = 0;        int i = 0;        while (i < s.size())        {            map<char,int>::iterator it = s_count.find(s[i]);            if (it == s_count.end())            {                s_count[s[i]] = i;            }            else            {                maxlength = max(maxlength, i - begin);                for (int j = begin; j < it->second; j++)                    s_count.erase(s[j]);                begin = it->second + 1;                s_count[s[i]] = i;            }            i++;        }        return max(maxlength, i - begin);        */    }};



阅读全文
0 0
原创粉丝点击