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

字符串练习(八):最长无重复字符子串

时间:2017-04-06 01:24:13      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:cts   longest   sam   div   distinct   ==   ring   练习   substr   

对于一个字符串,请设计一个高效算法,找到字符串的最长无重复字符的子串长度。

给定一个字符串A及它的长度n,请返回它的最长无重复字符子串长度。保证A中字符全部为小写英文字符,且长度小于等于500。

测试样例:
"aabcb",5
返回:3
public class DistinctSubstring {
    public int longestSubstring(String A, int n) {
        // write code here
        if(A==null || n==0){
            return 0;
        }
        char[] chas=A.toCharArray();
        int[] map=new int[256];//256个字符:记录每种字符之前出现的位置
        for(int i=0;i<256;i++){
            map[i]=-1;
        }
        int len=0;
        int pre=-1;
        int cur=0;//当前字符为止的最长无重复字符串的长度
        for(int i=0;i<n;i++){
            pre=Math.max(pre, map[chas[i]]);
            cur=i-pre;
            len=Math.max(len, cur);
            map[chas[i]]=i;
        }
        return len;
    }
}

 

字符串练习(八):最长无重复字符子串

标签:cts   longest   sam   div   distinct   ==   ring   练习   substr   

原文地址:http://www.cnblogs.com/gugibv/p/6671192.html

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