首页 > 其他 > 详细

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

时间:2019-03-06 10:45:46      阅读:129      评论:0      收藏:0      [点我收藏+]

题目:

请从字符串中找出一个最长的不含重复字符串的子字符串,计算该最长子字符串的长度。假设字符串中只包含‘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 }

技术分享图片

 

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

原文:https://www.cnblogs.com/wylwyl/p/10481158.html

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