leetcode -- 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.

从左往右扫描,当遇到重复字母时,以上一个重复字母的index +1,作为新的搜索起始位置。比如

直到扫描到最后一个字母。

 1 public class Solution {
 2     public int lengthOfLongestSubstring(String s) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         int[] count = new int[26];
 6         /*
 7         for(int i = 0; i < 26; i ++){
 8             
 9         }
10         */
11         resetCount(count);
12         
13         int sLength = s.length();
14         int maxL = 0;
15         int start = 0;
16         for(int i = 0; i < sLength; i++){
17             int index = s.charAt(i) - 97;
18             
19             if(count[index] >= 0){
20                 if(i - start > maxL){
21                     maxL = i - start;
22                 }
23                 // need to backtrack !!!
24                 i = count[index];
25                 start = i + 1;
26                 resetCount(count);
27                 continue;
28             }
29             
30             count[index] = i;
31             
32         }
33         
34         // if last round have no repeating characters, we should check
35         if(maxL < sLength - start){
36             maxL = sLength - start;
37         }
38         return maxL;
39     }
40     
41     public void resetCount(int[] count){
42         for(int i = 0; i < 26; i ++){
43             count[i] = -1;   
44         }
45     }
46 }

ref

http://fisherlei.blogspot.com/2012/12/leetcode-longest-substring-without.html

转载于:https://www.cnblogs.com/feiling/p/3139692.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值