zoukankan      html  css  js  c++  java
  • LeetCode_Longest Substring Without Repeating Characters

    Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
     
    分析:贪心法,从头扫描到尾,O(n)搞定 用一个map[256]来记录出现过的字符位置。遇到没有出现过的字符,将map对应位置标记,并且子串长度+1;遇到出现过的字符,将子串自上一次出现该字符位置前面的截断,对这部分截断的字符,标记map为notFound,重新计算子串长度
    参考: http://blog.unieagle.net/2012/09/30/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Alongest-substring-without-repeating-characters/
    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
             int map[256] ;
            
            for(int i = 0; i< 256; i++)
                 map[i] = -1;
                 
            const int Notfound = -1;    
            int firstPos = 0, lastPos = 0,len = 0;
            int i, j;
            int maxLen = 0;
            
            for(i = 0; i < s.size(); i++ )
            {
            
                int value = map[s[i]] ;
                
                if(value == Notfound)
                {
                    len++;
                    map[s[i]] = i;
                    maxLen = maxLen > len ? maxLen : len;
                }else{
                
                    lastPos = value;
                    for(j = firstPos ; j < lastPos ; j++)
                            map[s[j]] = Notfound ;
                    
                    firstPos = lastPos + 1;                
                    len = i - firstPos + 1;        
                    map[s[i]] = i;                
                }        
            }
            
            return maxLen ;
            
        }
    };
    
    
    
     
  • 相关阅读:
    三分
    知识点整合摘取
    Codeforces Round #533 C. Ayoub and Lost Array
    判断当前VC 是push还是present的
    自动布局
    获取当前的 viewController
    UIImageView 点击放大缩小
    UIButton 在UIScrollView里面 点击效果不明显的问题
    IOS AutoLayout 遍历修改约束
    GIT 命令 操作 记录
  • 原文地址:https://www.cnblogs.com/graph/p/3215279.html
Copyright © 2011-2022 走看看