Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

public class Solution {
    public int lengthOfLongestSubstring(String s) {
         if(s==null || s.isEmpty()==true)  //判断是否为空
            return 0;  
          
        int len = s.length();  
        int res = 1;              //长度变量
        int start = 0, cur = 1;  //起始位,游标
        int position[] = new int[256];  //利用字符的ASCII码值与数组的下标一一对应
        Arrays.fill(position, -1);  //将数组值全部设为-1
        position[s.charAt(0)] = 0;  //从第一位开始遍历,遍历后的字符对应数组中下标的值设为0
          
//      loop and find corresponding result  
        while(cur < len){  //遍历
//          s[cur] has not occurred  
            if(position[s.charAt(cur)] < start){  //当前遍历的字符之前没有遍历过,长度res加一,当前字符设为已遍历,数组值为0
                res = Math.max(cur-start+1, res);  
                position[s.charAt(cur)] = cur;  
            }  
//          s[cur] has occurred in previous substring  
            else{  
                start = position[s.charAt(cur)] + 1;  //当前字符已经遍历过,起始位加一
                res = Math.max(res, cur-start+1);  
                position[s.charAt(cur)] = cur;  
            }  
            cur++;  
        }// End while loop  
        return res;  
    }
}


转载于:https://my.oschina.net/u/2271480/blog/469507

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值