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;
        }
    };
  • 相关阅读:
    HTTP请求头的具体含意
    Python 之类与对象及继承
    PHP的一个牛逼的数组排序函数array_multisort
    mysqli返回受影响行数
    转:JS判断值是否是数字(两种方法)
    转:php中判断某个IP地址是否存在范围内
    php Closure::bind的用法(转)
    Drupal8入门文章推荐
    PHP通过api上传图片
    转:PHP中的使用curl发送请求(GET请求和POST请求)
  • 原文地址:https://www.cnblogs.com/LUO77/p/5727882.html
Copyright © 2011-2022 走看看