zoukankan      html  css  js  c++  java
  • 没有重复字符的子串的最大长度

    题目: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     int lengthOfLongestSubstring(string s) {
     2         
     3         int i, j;
     4         int maxLen = 0, begin = 0, cur = 0;
     5         set<char> cset;
     6         
     7         for (i = 0; i < s.size(); ++i)
     8         {
     9             if (cset.count(s[i]) == 0)
    10             {
    11                 cset.insert(s[i]);
    12                 cur++;
    13                 maxLen = (maxLen > cur) ? maxLen : cur;
    14             }
    15             else
    16             {
    17                 j = begin;
    18                 while (s[j] != s[i])
    19                 {
    20                     cset.erase(s[j]);
    21                     j++;
    22                 }
    23                 begin = j + 1;
    24                 cur = i - begin + 1;
    25             
    26             }
    27         }
    28         return maxLen;
    29     }

    方法二:网上找的一种代码,思路比较新颖,值得学习。代码如下:

     1     int lengthOfLongestSubstring(string s) {
     2         
     3         int c[256];
     4         int max, p, i;
     5         max = 0;
     6         p = 0;
     7         memset(c, -1, sizeof(c));
     8         
     9         for (i = 0; i < s.size(); ++i)
    10         {
    11             if (c[s[i]] < p)
    12             {
    13                 max = (max > (i - p + 1)) ? max : (i - p + 1);
    14             }
    15             else
    16             {
    17                 p = c[s[i]] + 1;
    18             }
    19             c[s[i]] = i;
    20         }
    21      
    22         return max;
    23     }

    总结:第一种方法采用传统的思想(即比较的方法)查询是否有重复的字符。第二种方法采用记录当前字符之前的所有字符出现的位置来判断是否有重复的字符,需要学习这种思想。

  • 相关阅读:
    catalina_home与catalina_base
    log4j配置
    lsof
    定时任务-crontab
    access日志配置
    java常识
    mysql事务隔离级别与实现原理
    文件描述符设置
    gpio 預設值
    synchronous interrupt and asynchronous interrupt
  • 原文地址:https://www.cnblogs.com/yyxayz/p/4038413.html
Copyright © 2011-2022 走看看