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

    分析:

      这题不难,但是需要注意一些细节,首先,必须要存储的信息有:(1)、当前最长无重复字符子串的起始位置。(2)、当前最长无重复字符子串的长度。(3)、由前两项信息可以截取字串,对下一个字符进行判断,若在字串中未找到该字符,则(1)中信息不变,(2)中信息要加1;若在字符串中找到该字符,返回该字符在字串中的位置,以(1)信息+重复位置+1作为新的起始位置,以(2)-重复位置作为新的(2)。

    代码如下:

    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            char cur;
            int max=1;
            int count=1;
            int index_begin,index_repeat;
            string curmax_string;
            if(s.length()==0)
            {
                return 0;
            }
            index_begin=0;
            for(int i=1;i<s.length();i++)
            {
                cur=s[i];
                curmax_string=s.substr(index_begin,count);
                if((index_repeat=curmax_string.find_last_of(cur))==string::npos)
                {
                    count++;
                    if(count>max)
                    {
                        max=count;
                    }
                }
                else
                {
                    count = count - index_repeat;
                    index_begin = index_begin+index_repeat+1;
                }
            }
            return max;
        }
    };
  • 相关阅读:
    设计模式之解释器
    mina学习
    我的学习网站(个人)
    jq实现剪裁图片设置为头像
    元素跟随着滚动条运动
    解决鼠标滚动的时候多次执行函数
    利用随机数生成一个简单的验证码
    自定义单选框或者复选框
    jquery实现旋转木马的插件slick
    js判断页面是pc打开还是手机打开
  • 原文地址:https://www.cnblogs.com/yanqi0124/p/4245005.html
Copyright © 2011-2022 走看看