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

  • 相关阅读:
    四则运算
    3.12----对potplayer的使用评价
    对软件工程的一点思考
    个人附加作业
    附加题
    个人最终总结
    结对编程总结
    修改后的四则运算
    阅读程序回答问题
    Visual studio 2013的安装和单元测试
  • 原文地址:https://www.cnblogs.com/feiling/p/3139692.html
Copyright © 2011-2022 走看看