菜鸡刷LeetCode

开贴记录刷LeetCode流程,防止自己忘了

第三题:

自己写的解,暴力算法。计算复杂度很高:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        
        int len =0;
        string str = "";//存储子字符串

        for(int i=0; i<s.length(); i++){
            for(int j=i;j<s.length(); j++){
                if(str.find(s[j]) == -1){//查找是否出现过该字符
                    str = str + s[j];//添加字符
                    len = len>str.length()?len : str.length();
                }
                else{
                    len = len>str.length()?len : str.length();
                    str = "";
                    break;
                }
            }
        }
        return len;
    }
};

hashmap:

class Solution
{
public:
    int lengthOfLongestSubstring(string s)
    {
        //s[start,end) 前面包含 后面不包含
        int start(0), end(0), length(0), result(0);
        int sSize = int(s.size());
        unordered_map<char, int> hash;
        
        while(end < sSize){
            
            char tmp = s[end];
            if(hash.find(tmp) != hash.end() && hash[tmp] >= start){//查找x是否在map中;预防abccadb这种情况,c是start,但是a在之前表里面出现过一次
                
                start = hash[tmp] +1;
                length = end -start;       
            }
            hash[tmp] = end;
            
            end++;
            length++;
            result = max(length,result);
        }

        return result;
    }
};
发布了7 篇原创文章 · 获赞 4 · 访问量 399

猜你喜欢

转载自blog.csdn.net/Alex_wise/article/details/105298998