最长不含重复字符的子字符串

题目:

请从字符串中找出一个最长的不含重复字符串的子字符串,计算该最长子字符串的长度。假设字符串中只包含'a'-'z'的字符。

 

解答:

 1 public class Solution {
 2 
 3     public static void main(String[] args) {
 4         String str "arabcacfr";
 5         System.out.println(findLongestSubstringLength(str));
 6     }
 7 
 8     public static int findLongestSubstringLength(String str) {
 9         if(str == null || str.equals("")) {
10             return 0;
11         }
12 
13         int maxLength = 0;
14         int curLength = 0;
15 
16         int[] positions = new int[256];
17         for(int i = 0; i < positions.length; i++) {
18             positions[i] = -1;
19         }
20 
21         for(int i = 0; i < str.length(); i++) {
22             int curChar = str.charAt(i) - 'a';
23 
24             int prePosition = positions[curChar];
25             int distance = i - prePosition;
26 
27             // 第一次出现或前一个非重复子字符串不包含当前字符
28             if(prePosition < 0 || distance > curLength) {
29                 curLength++;
30             } else {
31                 if(curLength > maxLength) {
32                     maxLength = curLength;
33                 }
34 
35                 curLength = distance;
36             }
37 
38             positions[curChar] = i;
39         }
40 
41         if(curLength > maxLength) {
42             maxLength = curLength;
43         }
44 
45         return maxLength;
46     }
47 }

 

posted @ 2019-03-06 09:00  林木声  阅读(708)  评论(0编辑  收藏  举报