• 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)

  • 相关阅读:
    Git 数据是怎么存储的
    技术管理规划-路径跟资源
    技术管理规划-如何规划团队的架构
    技术管理规划-如何设定团队的目标
    技术管理规划-设定团队的职能
    springboot实践1
    spring的事件机制实战
    Apollo的基本概念和集成实战
    spring的事件
    ELK的简单安装使用
  • 原文地址:https://www.cnblogs.com/hf-cherish/p/4571217.html
Copyright © 2020-2023  润新知