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;
        }
    };
    
  • 相关阅读:
    快速幂
    hdu 1595 find the longest of the shortest(迪杰斯特拉,减去一条边,求最大最短路)
    hdu 4121 Xiangqi
    hdu 2224 The shortest path
    hdu4923
    矩阵模板
    hdu4570(区间dp)
    hdu1978(记忆化搜索)
    hdu4283(区间dp)
    hdu1160最长递减子序列及其路径
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6756120.html
Copyright © 2011-2022 走看看