zoukankan      html  css  js  c++  java
  • 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.

    思路:一遍遍历一边记录最大长度。如果出现重复字符,则从当前不重复的cursub string中截取重复位置之后的substr,并与重复字母拼接成新的cursub,判断新的cursub长度是否超过当前所知的最长。

    复杂度分析:O(n) ,我的解法38ms,但leetcode有更快!待我研究下

    开心的是又一次 bug free!

    总结:3种解法:(1)string (2)two pointer (3)hashtable!  哇这么多方法。

    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            //check validation
            if(s.empty()) return 0;
            //check specail case or bound;
            int len=s.length();
            if(len==1) return 1;
            
            //general case
            string cursub;
            cursub=s[0];
            int lmax=1;
            int lcur=1;
            for(int i=1;i<len;i++){
                int pos=cursub.find(s[i]);
                if(pos>=0){
                    if(pos+1==lcur) cursub.clear();
                    else
                        cursub = cursub.substr(pos+1,cursub.length()-pos);
                }
                cursub+=s[i];
                lcur=cursub.length();
                if(lcur>lmax) lmax=lcur;
            }
            return lmax;
        }
    };
  • 相关阅读:
    AOP 和 前置通知,后置通知
    使用Spring 简化MyBatis
    核心一:DI
    环境搭建及创建对象方式及赋值(注入)
    核心一:IoC
    Spring框架简介
    判断两个矩形是否相交的4个方法
    计算旋转角度
    浅析adb命令
    如何选择开源许可证?
  • 原文地址:https://www.cnblogs.com/renrenbinbin/p/4439103.html
Copyright © 2011-2022 走看看