Longest Substring Without Repeating Characters

来源:互联网 发布:linux搭建dns教程 编辑:程序博客网 时间:2024/06/03 23:46

使用两个指针 i , j , 从前向后遍历数组,如果遇到已存在的字符,应该回退到这个字符上次出现的下一个位置从新开始统计。

用哈希表存储字符出现的位置可以把查询时间降低到O(1)。

class Solution {public:/*Use left pointer i and right pointer j.When we met s[j] which is already between [i,j], we update left pointer i.And what we need finally is return the max of j-i*/int lengthOfLongestSubstring(string s) {unordered_map<char, int> charMap;int maxLen = 0, i, j;for (i = 0, j = 0; j<s.size(); j++) {//Update left pointer and update maxLenif (charMap.find(s[j]) != charMap.end() && charMap[s[j]] >= i) {maxLen = maxLen >(j - i) ? maxLen : (j - i);i = charMap[s[j]] + 1;}charMap[s[j]] = j;}return maxLen > (j - i) ? maxLen : (j - i);;}};


0 0
原创粉丝点击