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;
        }
    };
  • 相关阅读:
    webAPI身份验证
    vs调试的时候debug和release的区别
    webapi put 请求405问题
    WebApi跨域问题解决
    多车轨道路径规划算法设计
    Re:从零开始学流媒体(一):视频跳转、206、chunked、动态URL、断点续传
    Java面试题总结论(二)-IOC、AOP、Spring、注解
    Java面试题总结论(一)-数据结构
    从零开始部署发布Java项目到服务器的Docker中
    10天,从.Net转Java,并找到月薪2W的工作(三)
  • 原文地址:https://www.cnblogs.com/LUO77/p/5727882.html
Copyright © 2011-2022 走看看