Leetcode 3. Longest Substring Without Repeating Characters
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.
C++:(vector容器)
class Solution { public: int lengthOfLongestSubstring(string s) { vector<int> dict(256, -1); //dict有256个元素,每个值都是 -1 int maxlen = 0,start = -1; for(int i = 0;i != s.length(); i++) { if(dict[s[i]] > start) start = dict[s[i]]; //返回dict中第s[i]个位置上的引用 dict[s[i]] = i; maxlen = max(maxlen, i - start); } return maxlen; } };
C++:(关联容器map)
class Solution { public: int lengthOfLongestSubstring(string s) { map<char, int> hash; //map(有key和value组成)的遍历,和其它STL的容器一样,都是通过迭代器实现 int maxlen = 0,start = 0; for(int i = 0; i < s.length();++i) { if(hash[s[i]] == 0 || (hash[s[i]] != 0 && start > hash[s[i]])) { maxlen = maxlen > (i - start + 1) ? maxlen : (i - start + 1); } else start = hash[s[i]]; hash[s[i]] = i + 1; } return maxlen; } };
Python:
class Solution: def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ start = maxLen = 0 dict_s = {} # 字典是另一种可变容器模型,且可存储任意类型对象 for i in range(len(s)): if s[i] in dict_s and start <= dict_s[s[i]]: start = dict_s[s[i]] + 1 else: maxLen = max(maxLen, i -start + 1) dict_s[s[i]] = i return maxLen

浙公网安备 33010602011771号