zoukankan      html  css  js  c++  java
  • 一起刷LeetCode3-Longest Substring With Repeating Characters

      拖延症太严重了TAT,真心要处理一下这个问题了,感觉很不好!

    ----------------------------------------------------------------------------------------------------------------

    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.

    【题意】:这道题的意思是说,给你一个字符串,让你找出最长字串要求没有重复字符的长度。比如,

    字符串“abcabcbb”里最长的不重复字符串是“abc”,所以最后的答案是3

    【心路历程】:刚开始看这道题的时候其实没啥想法,最直接的想法是枚举,O(n*2)的时间复杂度,肯定是不行的,就算能过

    也不是最好的,所以直接pass掉这种想法。于是,开始往dp的方向想,想了一会发现找不到可以构建的动态转移方程。

    之后就是深陷思考的漩涡中。。。

    后来考虑用一个数组index记录当前位置下每个字符最后出现的位置,一个下标cur维护当前的字符串开始位置。

    遍历一遍字符串,当这个字符没出现过时,cur不变,最大长度加1。

    当这个字符出现过时,cur变为字符上次出现位置加1。不断维护没有重复字符的一个字符串,和一个最大长度的变量。

    ----------------------------------------------------------------------------------------------------------------------

    代码如下:

     1 int lengthOfLongestSubstring(char* s) {
     2     int index[256];
     3     int len = strlen(s);
     4     int i,max = 0,ans = 0,cur = 1;
     5     memset(index,0,sizeof(index));
     6     for( i = 0; i < len; i++) {
     7         int c = (int)(s[i]);
     8         if(!index[c] || index[c] < cur){
     9             index[c] = i+1;
    10             max = i - cur + 2;
    11             if(max > ans) ans = max;
    12         }else {
    13             cur = index[c] + 1;
    14             max = i+1 - index[c];
    15             index[c] = i + 1;
    16             if(max > ans) ans = max;
    17         }
    18     }
    19     return ans;
    20 }
  • 相关阅读:
    Windows Server 2008 R2 下配置证书服务器和HTTPS方式访问网站
    C# AD(Active Directory)域信息同步,组织单位、用户等信息查询
    Windows Server 2008 R2 配置Exchange 2010邮件服务器并使用EWS发送邮件
    体验vs11 Beta
    jQuery Gallery Plugin在Asp.Net中使用
    第一个Python程序——博客自动访问脚本
    网盘:不仅仅是存储
    TCP/UDP端口列表
    Linux的时间 HZ,Tick,Jiffies
    Intel Data Plane Development Kit(DPDK) 1.2.3特性介绍
  • 原文地址:https://www.cnblogs.com/LeeZz/p/4491449.html
Copyright © 2011-2022 走看看