3 Longest Substring Without Repeating Characters

来源:互联网 发布:sql注入防止php 编辑:程序博客网 时间:2024/05/18 18:55

Leetcode 3:

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.

一开始的想法是使用map,如果map是一个队列的话,每次遇到重复的就将重复元素之前的全删掉,然后再insert新元素,始终保持map中存储的是没有重叠元素的子string。但是后来调试发现,map中的元素存放是经过排序的,所以失败。将map定义为unordered_map,可以得到正确的答案。但是提交之后却不能AC,应该是编译器的问题。所以放弃这种方法。

另外,可以用一个256长度的数组,数组下标为string中的char元素。设置一个flag标志子string的起始位置,然后遍历string。这样就能得到一个耗时o(N),内存o(1) 的答案。


class Solution {public:int lengthOfLongestSubstring(string s) {int my_size = 0;int flag = 0;vector<int> my_vector(256,-1);for (int i = 0; i < s.size(); i++){if (my_vector[s[i]] < flag){my_vector[s[i]] = i;}else{flag = my_vector[s[i]]+1;my_vector[s[i]] = i;}if (i - flag + 1 > my_size){my_size = i - flag + 1;}}return my_size;}};


0 0