3. Longest Substring Without Repeating Characters--2016/09/19

来源:互联网 发布:js对象属性的访问方法 编辑:程序博客网 时间:2024/06/01 07:18

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 subsequence and not a substring.

思路:依次遍历存入hashmap,不断更新左边界,注意左边界初始值为1,每次遍历都要插入/更新对应char的map表,并更新最长子串长度

class Solution {public:    int lengthOfLongestSubstring(string s) {        map<char,int> charMap;        int subLength = 0;        //当前左边界,注意起始值为-1        int startIndex = -1;        for(int i=0;i<s.size();i++)        {            //之前有重复的            if(charMap.find(s[i]) != charMap.end())            {                //更新左边界                startIndex = max(startIndex,charMap[s[i]]);            }            //插入/更新map的value            charMap[s[i]] = i;            //更新最大子串长度            subLength = max(subLength,i-startIndex);        }        return subLength;    }};
0 0
原创粉丝点击