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

    1. Question

    求最长无重复字符子串。

    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.
    

      

    2. Solution

    定义如下三个变量:

    • i:指示候选最长子串串首,初值为0。
    • j:指示候选最长子串串尾,初值为0。
    • sub:代表候选最长子串,初值为第一个字符。
     1 for( ; i<=len; ){
     2     for( ; j<=len; j++ )
     3         判断chars[j]是否在sub中{
     4             如果在{
     5                 i = sub中chars[j]的位置+1;
     6                 j++;
     7                 修改sub;
     8                 break;
             }
    9 } 10 }
     1 public class Solution {
     2     //O(n2) time
     3     public int lengthOfLongestSubstring( String s ){
     4         if( s.length() <= 1 ) return s.length();
     5         int len = 0;
     6         int from = 0;
     7         int end = 1;
     8         for( int i=1; i<s.length(); i++ ){
     9             int index = s.substring(from, end).indexOf(s.codePointAt(i));        // O(n) time
    10             //the present char can be added to the substring
    11             if( index<0 )
    12                 end++;
    13             //the present char is an duplicate for this substring
    14             else{
    15                 len = ( end-from > len ) ? (end-from) : len;
    16                 from += index+1;
    17                 end++;            
    18             }
    19         }
    20         
    21         len = ( end-from > len ) ? (end-from) : len;    
    22         
    23         return len;
    24     }
    25 }
    lengthOfLongestSubstring

    3. 复杂度分析

    外循环遍历字符串,内循环遍历候选子串。时间复杂度O(n2)

  • 相关阅读:
    ASP.NET2.0中用Gridview控件操作数据
    有关petShop的几篇文章
    用多活动结果集优化ADO.NET2.0数据连接
    设计数据层组件并在层间传递数据
    google的语法?
    PHP导出Excel方法
    header ContentType类型
    40条优化php代码的小实例
    strstr 不错的技巧
    PHP 截取字符串专题
  • 原文地址:https://www.cnblogs.com/hf-cherish/p/4571217.html
Copyright © 2011-2022 走看看