Leetcode 3 - Longest Substring Without Repeating Characters

来源:互联网 发布:java 计算法定节假日 编辑:程序博客网 时间:2024/05/16 06:26

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.

1 - 使用哈希表存储每个字符出现的位置。
2 - 采用滑动窗口法计算最大长度。窗口左端位置初始化为0,窗口右端不断向右移动。若窗口右端遇到已经出现过的字符,则将窗口左端位置设置在已出现字符的后一位。

class Solution {public:    int lengthOfLongestSubstring(string s) {        unordered_map<char,int> map;        int result = 0;        int begin = 0;        for(int i=0;i<s.length();i++){            //遇到已经出现过的字符,且该字符的位置在begin之后            if(map.find(s[i])!=map.end() && map[s[i]]>=begin){                begin = map[s[i]] + 1;            }            result = max(result,i-begin+1);            map[s[i]] = i;        }        return result;    }};
0 0