码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 3 - Longest Substring Without Repeating Characters

时间:2016-08-02 01:18:49      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

原题如下:

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

使用动态规划,分别计算前n个字符中以最后一个字符结尾的最长不重复子串,最后计算一下其中的最大值,时间复杂度为O(n*n+n)=O(n^2)。代码如下:

 1     public int lengthOfLongestSubstring(String s) {
 2         if(s.length() == 0){
 3             return 0;
 4         }
 5         int[] A = new int[s.length()];
 6         A[0] = 1;
 7         int max = 1;
 8         for(int i = 1; i< s.length(); i++){
 9             if(s.charAt(i) == s.charAt(i-1)){
10                 A[i] = 1;
11             }else{
12                 int j = 1;
13                 for(; j < A[i-1]+1; j++){
14                     if(s.charAt(i) == s.charAt(i-j)){
15                         break;
16                     }
17                 }
18                 A[i] = j;
19             }
20             if(max < A[i]){
21                 max = A[i];
22             }
23         }
24         return max;
25     }

参考源码:https://github.com/pkufork/Martians/blob/master/src/main/java/com/pkufork/martians/leetcode/LongestSubstringWithoutRepeatingCharacters3.java

LeetCode 3 - Longest Substring Without Repeating Characters

标签:

原文地址:http://www.cnblogs.com/pkufork/p/ds_leetcode_3.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!