[leetcode] Longest Substring Without Repeating Characters

来源:互联网 发布:淘宝类目分析模板 编辑:程序博客网 时间:2024/06/09 18:20

From : https://leetcode.com/problems/longest-substring-without-repeating-characters/

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.

class Solution {public:    int lengthOfLongestSubstring(string s) {        int ans=0, sz=s.size(), idx=0;        map<char, int> box;        vector<int> pre(sz, -1);        for(int i=0; i<sz; i++) {            if(box.find(s[i]) != box.end()) pre[i] = box[s[i]];            box[s[i]] = i;        }        for(int i=0; i<sz; i++) {            if(pre[i] != -1  &&  pre[i]>=idx) {if(ans < i-idx) ans = i-idx;                idx = pre[i]+1;            }        }        return max(ans, sz-idx);    }};

改进:

class Solution {public:    int lengthOfLongestSubstring(string s) {        vector<int> locs(256, -1);        int idx = -1, max = 0;for (int i=0, sz=s.size(); i<sz; i++) {            if (locs[s[i]] > idx) idx = locs[s[i]];            if (i - idx > max) max = i - idx;            locs[s[i]] = i;        }        return max;    }};


0 0