首页 > 其他 > 详细

Longest Substring Without Repeating Characters

时间:2015-06-12 16:45:47      阅读:200      评论:0      收藏:0      [点我收藏+]

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)

Longest Substring Without Repeating Characters

原文:http://www.cnblogs.com/hf-cherish/p/4571217.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!