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.

思路:

已知:字符串数组char s[], 长度为s.length,所求的返回值设为length,初始化为length =0;

假设: 一个长度为s.length的数组int count[],初始化初值均赋值为0. 

目标:count[i]记录s[i]所对应的向前查看的最长不重复字符子串的长度值;则由length记录最大值,遍历一次即找到最大的值!

思路证明:

a). 当s.length = 0时,length =0,肯定正确;当s.length =1时,length=1,肯定正确;
b). 当count[i-1]正确时,count[i]的计算肯定正确,那么整个计算过程肯定正确!


算法步骤:

1. 当字符串string s为空时,返回值为length = 0;当字符串string s长度为1时,返回值length = 1;

2. 假设count[i-1]之前的所有count[0] ---count[i-1]的值都是正确的,那么count[i]的值为,向前探索count[i-1]次,若没有重复字符,则值自加1;若有重复字符,则停止,count[i]的值即为当前值。故count[i]的取值范围为(1,count[i-1]+1).

3. 用length记录最大的count[i],最后返回length!

代码:

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int length = 0; // for return
        char ch[] = s.toCharArray();   
        int count[] = new int[ch.length];
        if(ch.length == 0){
            return 0;
        }else if(ch.length == 1){
            return 1;
        }else{
			count[0] = 1;
			for(int i = 1; i < ch.length; i++){
				count[i] = 1;
				for(int j = i-1; j >= (i-count[i-1]); j--){
					if(ch[i] != ch[j]){
						count[i]++;
					}else{
						break; // break this circle
					}
				} // for(j)
				length = (length< count[i]) ? count[i]:length; // get the max count[i]
			} // for(i)
			return length;
		}// else
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值