zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    软工实践总结
    Beta总结
    beta冲刺6/7
    beta冲刺5/7
    Beta冲刺4/7
    beta冲刺3/7
    beta冲刺2/7
    beta冲刺1/7
    答辩总结
    ES6中的块级作用域与函数声明
  • 原文地址:https://www.cnblogs.com/feiling/p/3139692.html
Copyright © 2011-2022 走看看