3. Longest Substring Without Repeating Characters

来源:互联网 发布:md5解密算法java程序 编辑:程序博客网 时间:2024/06/08 05:09

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.

Python:

class Solution(object):    def lengthOfLongestSubstring(self, s):        """        :type s: str        :rtype: int        """        start = 0        maxlength = 0        usedchar = {}        for i in range(len(s)):            if s[i] in usedchar and start <= usedchar[s[i]]:                start = usedchar[s[i]] + 1            else:                maxlength = max(maxlength,i - start + 1)            usedchar[s[i]] = i        return maxlength

C++:

class Solution {public:    int lengthOfLongestSubstring(string s) {        vector<int> dict(256,-1);        int maxlen = 0,start = 0;        for(int i = 0;i != s.length(); ++i){            if(start <= dict[s[i]]){                start = dict[s[i]] + 1;            }            maxlen = max(maxlen,i - start + 1);            dict[s[i]] = i;        }        return maxlen;    }};
阅读全文
0 0
原创粉丝点击