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)

  • 相关阅读:
    超详细动画彻底掌握深度优先,广度优先遍历!
    拜托,别再问我什么是 B+ 树了
    高性能短链设计
    Gradle build 太慢,可能是你使用的姿势不对
    看完这些,你也能成技术专家
    x58平台 服务器电源配置 tdp
    系统掉盘,机械硬盘掉盘,固态掉盘
    centos7 修改ip和dns
    centos 修改hostname
    TCP三次握手和四次挥手过程
  • 原文地址:https://www.cnblogs.com/hf-cherish/p/4571217.html
Copyright © 2011-2022 走看看