3. Longest Substring Without Repeating Character[M] 最大不重复子串

题目


Given a string, find the length of the longest substring without repeating characters.
Example 1:
 Input:"abcabcbb"
  Output:3
 Explanation:The answer is "abc",with the length of 3.
Example 2:
 Input:"bbbb"
 Output:1
 Explanation:The answer is "b",with the length of 1.
Example 3:
 Input:"pwwkew"
 Output:3
 Explanation: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.

思路


思路1:滑动窗口法

首先分析题意,这题是求一个最长不重复子串,需要注意两点:一是不重复;二是子串,不是子序列,这意味着字符必须连续。

思路2:滑动窗口法优化

用ASCII表中字符与十进制整数之间的映射,来代替思路一通过哈希表建立的字符与该字符在字符串中最后出现的位置之间的映射。由于ACSII表共能表示256个字符,因此我们可以建立一个256维的数组来代替哈希表,并将数组的每个元素初始化为-1。这样就不用查找字符的映射,对于遍历到的每个字符,更新他在数组对应位置(根据ASCII表将字符转化为对应的int),再用数组的元素来更新窗口的左边界。这样,不用专门建立映射,而是根据ASCII表字符与整数的映射,加快速度。

C++


  • 思路1
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        
        unordered_map<char,int> map;  //建立字符与该字符在s中最后出现的位置之间的映射
        int left = -1; // 左边界
        int result = 0; //长度
        for(int i = 0;i < s.size(); i++){
            
            if(map.count(s[i]) && map[s[i]] > left)
                left = map[s[i]];

            map[s[i]]=i;
            result = max(result, i-left);           
        }
        return result;
    }
};
  • 思路2
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        
        vector<int> map(256,-1);
        int left = -1;
        int result = 0;
        for(int i = 0;i < s.size(); i++){
            
            if(map[s[i]] > left)
                left = map[s[i]];

            map[s[i]]=i;
            result = max(result, i-left);      
        }
        return result;
    }
};

Python

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        
        table = { }
        left = -1
        result = 0
        for i in range(len(s)):
            if (s[i] in table) and table[s[i]] > left:
                left = table[s[i]]
            
            table[s[i]] = i
            result = max(result, i - left)
            
        return result

猜你喜欢

转载自www.cnblogs.com/Jessey-Ge/p/10988584.html
今日推荐