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.

    以下用map记录关键信息,得到了O(n)的解法:

    class Solution {
        public:
            int lengthOfLongestSubstring(string s) {
               if(s.size()<2)
                   return s.size();
               int lengthOfCurrent=1,maxLength = 1; //lengthOfCurrent表示当前字符往前具有的不重复字符个数。
               map<char,int> m;                     //m里存放字符及字符在s中的下标。
               m[s[0]]=0;
               for(int i = 1;i<s.size();i++)
               {
                   if(m.count(s[i])==0 || m[s[i]]<i-lengthOfCurrent)//当前字符没与之前重复 或者 重复了但在前一个字符重复字符之前,对当前最大长度没有影响
                       lengthOfCurrent++;
                   else
                       lengthOfCurrent = i -  m[s[i]];
                   m[s[i]] = i;
                   if(lengthOfCurrent>maxLength)
                       maxLength = lengthOfCurrent;
    
               }
    
    
               return maxLength;
            }
        };
  • 相关阅读:
    Git
    vue
    vue
    echarts,dojo和兼容问题
    js数组对象以某一对象排序
    滚动条与图片移动
    vue
    vue
    vue页面组件化-父子组件传值
    phpquery笔记
  • 原文地址:https://www.cnblogs.com/Xylophone/p/3870655.html
Copyright © 2011-2022 走看看