zoukankan      html  css  js  c++  java
  • 【leetcode】3. Longest Substring Without Repeating Characters

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

    Examples:

    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.

    其实思路还是蛮简单的,首先必须是子串,子串必须连续,连续首先想到的就是字符串扫描,也就是循环。(试图用递归做,比较恶心)

    扫描过程中就是收集substr的过程,如果没有重复的字符,就把该字符收进substr,然后和maxlen比较,maxlen记最大的substr长度。

    如果出现重复字符,判断是否已经到原来字符串的尾巴,如果到了就返回maxlen,如果没到,就要更新substr,更新substr的过程中先不需要跟maxlen有什么变化。

    注意点:

    string自己的find函数好像不好用,返回下标,没找到返回std::npos。

    string自己的substr函数原型是  substr(int start,int len);

    最后用的是stl里的find:Template<T>::iterator find(iterator begin,iterator end,T need);

    用的string的构造函数  string(iterator begin,iterator end);

    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            int len=s.length();
            if(len==0||len==1)
                return len;
            string substr="";
            int maxlen=0;
            for(int i=0;i<len;i++){
                if(find(substr.begin(),substr.end(),s[i])==substr.end()){
                    substr+=s[i];
                    if(substr.length()>maxlen)
                        maxlen=substr.length();}
                    else{
                        auto j=find(substr.begin(),substr.end(),s[i]);
                        if(j==s.end()-1)
                            return maxlen;
                        if(j==substr.end()-1){
                            substr="";
                            substr+=s[i];}
                        else {
                            string tmp(j+1,substr.end());
                            tmp+=s[i];
                            substr=tmp;
                        }
                    }
                }
            if(substr.length()>maxlen)
                maxlen=substr.length();
            return maxlen;
        }
    };
  • 相关阅读:
    虚拟化VMware之虚拟机备份(1)
    虚拟化VMware之虚拟机备份(1)
    柯塔娜大合唱,互联网安全观
    柯塔娜大合唱,互联网安全观
    如何在虚拟机上Centos系统安装Nginx服务
    给已验证登录的用户添加访问限制
    Python爬虫入门教程 23-100 石家庄链家租房数据抓取
    login_required装饰器(1)
    Oracle 18c 新特性:动态 Container Map 增强 Application Container 灵活性
    如果登录不成功,跳转到登录页面
  • 原文地址:https://www.cnblogs.com/LUO77/p/5727882.html
Copyright © 2011-2022 走看看