LeetCode Day3 Longest_Substring_Without_Repeating_Characters

C++

我的解法:
使用另一个string变量tmp存储子串,把没出现过的加入,碰到出现过的从左开始删除,直到删到未出现的。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if(s.size()!=0){
        string tmp(s,0,1);
        int len=1;int max=0;int loc;
        for(int i=1;i<s.size();i++){
            if(tmp.find(s[i],0)==string::npos){
                len++;
                tmp.append(1,s[i]); 
            }
            else{
                max=(len>max)?len:max;
                loc=tmp.find(s[i],0);
                tmp.erase(0,loc+1);
                len-=(loc+1);
                tmp.append(1,s[i]);len++;
            }
        }
        max=(len>max)?len:max;
        return max;}
        else return 0;
    }
};

Hash Map:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int m[256] = {0}, res = 0, left = 0;
        for (int i = 0; i < s.size(); ++i) {
            if (m[s[i]] == 0 || m[s[i]] < left) {
                res = max(res, i - left + 1);
            } else {
                left = m[s[i]];
            }
            m[s[i]] = i + 1;
        }
        return res;
    }
};

使用Python复现HashMap解法:

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        maxium=0;left=0;hashmap=[0]*256
        for i in range(len(s)):
            if hashmap[ord(s[i])]!=0 and hashmap[ord(s[i])]>left:
                left=hashmap[ord(s[i])]
            else:
                maxium=max(maxium,i-left+1)
            hashmap[ord(s[i])]=i+1
        return maxium

精简:

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        maxium=0;left=0;
        hashmap=[0]*256
        for i in range(len(s)):
            left=max(hashmap[ord(s[i])],left)
            hashmap[ord(s[i])]=i+1
            maxium=max(maxium,i-left+1)
        return maxium

猜你喜欢

转载自blog.csdn.net/weixin_41394379/article/details/82937099