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 };

 

转载于:https://www.cnblogs.com/flowerkzj/p/3621681.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值