3. Longest Substring Without Repeating Characters

来源:互联网 发布:云计算与物联网的关系 编辑:程序博客网 时间:2024/06/10 00:55

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.

思路:用unordered_map会超时。也可能包含非字符的。

class Solution {public:    int lengthOfLongestSubstring(string s) {        int hash[256];        for (int i = 0; i<256; i++) hash[i] = -1;        int maxLen = 0;        int start = 0, newstart = 0;        int i = 0;        for(i = 0; i < s.size(); i++)        {            if (hash[s[i]] != -1)            {                if (maxLen < i - start) maxLen = i - start;                newstart = hash[s[i]] + 1;                for (int j = start; j <= hash[s[i]]; j++) hash[s[j]] = -1;                start = newstart;            }            hash[s[i]] = i;        }        return max(i - start, maxLen);    }};
0 0
原创粉丝点击