zoukankan      html  css  js  c++  java
  • Leetcode: 3. Longest Substring Without Repeating Characters

    Description

    Given a string, find the length of the longest substring without repeating characters.

    Example

    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.
    

    思路

    • hash,将字符和出现位置进行hash
    • 对字符串从头到尾扫描一遍,维护一个不重复的子串。记录一个起始位置到当前位置为子串。
    • 扫描过程中,若出现相同字符,根据hash情况,判断此时的子串是否应该改变起始位置。

    代码

    • 时间复杂度 O(n)
    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            int len = s.size();
            if(len == 0) return 0;
            
            vector<int> hash(256, -1);
            int max_len = 0, begin = 0;
            
            for(int i = 0; i < len; ++i){
                if(i == begin){
                    hash[s[i]] = i;
                    begin = i;
                }
                
                //判断该字符是否已经出现过,而且需要判断是否应该改变起始位置
                //若该字符的最近出现位置小于begin,即说明不在当前子串中,不需要改变
                else if(hash[s[i]] != -1 && hash[s[i]] >= begin){
                     begin = hash[s[i]] + 1;   
                }
                
                //修改s[i]最近出现位置
                hash[s[i]] = i;
               
                if(i - begin + 1 > max_len)
                    max_len = i - begin + 1;
            }
            
            return max_len;
        }
    };
    
  • 相关阅读:
    python3+requests库框架设计03-请求重新封装
    python3+requests库框架设计02-封装日志类
    [patl2-001]紧急救援
    [patl1-046]整除光棍
    latex学习
    matlab基础功能实践
    dll注入及卸载实践
    编译原理大作业暂存
    12.24逆向工程上机作业整理
    [poj1703]Find them, Catch them(种类并查集)
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6756120.html
Copyright © 2011-2022 走看看