zoukankan      html  css  js  c++  java
  • Leetcode OJ: Longest Substring Without Repeating Characters

    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.

    求出不存在重复字符的子串的最大长度。

    这里有两个问题:

    一个是判断重复,字符串只有256个可能,因此一个256大小的数组足矣。

    一个是求最大长度,最简单粗暴的方法当然是把所有的子串都列出来,然后比出长度最大的,复杂度为O(n^2)

    有没有剪枝的方案呢?先观察如果遍历一次,出现第一个重复的时候会怎样。

    字符串:abcdcbaba

    这里第一次遇到有重复的是c:abcdcbaba

    现在为止最长的就是abcd,长度为4了,第1个c前的子串是没必要比较了,因为再比也会比4小,而之后的就不一定了。

    根据这样的观察结果,我们就只需要根据重复点在子串中的位置进行跳转,不需要无谓的比较了。

    于是我们的hash就不仅仅是用来存是否出现过了,而是要存放出现的位置。

    代码如下:

     1 class Solution {
     2 public:
     3     int lengthOfLongestSubstring(string s) {
     4         if (s.empty())
     5             return 0;
     6         size_t i = 0, j = 1;
     7         size_t size = s.size();
     8         int max_count = 0;
     9         int count = 1;
    10         vector<int> hash(256, -1);
    11         hash[s[0]] = 0;
    12         while (i < size && j < size) {
    13             if (hash[s[j]] < 0) {
    14                 hash[s[j]] = j;
    15                 count++;
    16             } else {
    17                 if (max_count < count)
    18                     max_count = count;
    19                 while (i < hash[s[j]]) {
    20                     hash[s[i]] = -1;
    21                     i++;
    22                     count--;
    23                 }
    24                 hash[s[j]] = j;
    25                 i++;
    26             }
    27             ++j;
    28         }
    29         if (max_count < count)
    30             max_count = count;
    31         return max_count;
    32     }
    33 };
  • 相关阅读:
    zabbix客户端自动注册
    运维监控篇(2)_Zabbix简单的性能调优
    Zabbix unreachable poller processes more than 75% busy
    RabbitMQ 内存控制 硬盘控制
    RabbitMQ的Q&A
    RabbitMQ性能优化
    消息默认的属性
    RabbitMQ的Vhost,Exchange,Queue原理分析
    逻辑运算符(&& || and or)
    面向对象
  • 原文地址:https://www.cnblogs.com/flowerkzj/p/3621681.html
Copyright © 2011-2022 走看看