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.

题目的意思是给定一个字符串,找出最长的不重复的子串的长度。比如“abcabcbb”的最长的不重复的子串为“abc”其长度为3;“bbbbb”的最长的不重复的子串为“b”,其长度为1

思路:
遍历字符串s,如果s中当前字符与子串中字符重复,那么就先找到子串中与当前重复的字符的下标c,然后子串的开始位置current就应该为c+1

比如:s1=ebabcadefg
遍历s1 此时子串为eba,再往后,s1中当前字符为b与子串中的字符重复,那么先计算出此时子串的长度,更新result的值,然后找到子串中重复字符b的下标为1,那么就将子串的开始位置变为2,也就是子串再从a开始,因为如果子串中继续包括b的话会有重复的数字,不过在遍历s的过程中要不断的更新result的值,以便记录下最新的最大的不重复子串的长度。

注意:
1. 用一个数组来表示出现的字符的下标(由于ASCII码由8位表示,共可以表示256个字符,所以这个下标数组的长度为256),先将字符串s中的字符在下标数组中的值初始化为-1,比如若s中有‘a’,‘a’的ASCII码为97,那么就有hash[97]=-1
2. 用current表示当前子串的第一个字符的下标,在current之前的都是无效的,current初始值为0。 用result来记录当前算得的最长的不重复的子串的长度。

public class Solution {
    public int lengthOfLongestSubstring(String s) {
            int result = 0;
        int current = 0;
        int strLength = s.length();
        // hash数组是用来s中字符的下标
        int[] hash = new int[256];
        for (int i = 0; i < strLength; i++)
            hash[s.charAt(i)] = -1;
        for (int i = 0; i < strLength; i++) {
            // 说明出现了重复的字符
            if (hash[s.charAt(i)] >= current) {
                result = Math.max(result, i - current);
                current = hash[s.charAt(i)] + 1;
                hash[s.charAt(i)] = i;
            }
            // 若没有出现重复的数字那就更新不重复字符串的长度,并更新hash表
            else {
                result = Math.max(result, i - current + 1);
                hash[s.charAt(i)] = i;
            }
        }
        return result;
    } 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值