求最长无重复字符的substring的长度

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int length = s.length();
        int begin=0,end=0,maxLength=0,temp=0;//begin和end是所求substring的头尾位置
	/*
	 * 计算机中ASCII码所能表示的字符个数是256
	 * 该数组的下标是每个字符对应的ASCII码
	*/
        boolean[] isExist = new boolean[256];//是否存在该字符的boolean数组
        int[] position = new int[256];//字符的位置
        
        for(int i = 0;i<length;i++){
            char c = s.charAt(i);
            end = i;
            if(isExist[c]){
                /*
                * 如果存在该字符,则计算maxLength,并且截去该字符上一次出现位置之前的字符(boolean置为false)
                * 重新确定begin
                */
                temp = maxLength;//存储上一次的maxLength
                maxLength = end - begin;
                if(maxLength<temp){
                    maxLength = temp;
                }
                for(int j = begin;j<position[c]+1;j++){
                    char d = s.charAt(j);
                    isExist[d] = false;
                }
                begin = position[c]+1;
            }
	        isExist[c]=true;
            position[c]=i;
    	    /*
    	    *如果是最后一个字符,则直接计算出maxLength
    	    */
    	    if(end == length-1){
            	temp = maxLength;
            	maxLength = end-begin+1;
            	if(maxLength<temp){
            	    maxLength = temp;
            	}
            }
        }
        return maxLength;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值