Leetcode 3(Java)

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given “abcabcbb”, the answer is “abc”, which the length is 3.

Given “bbbbb”, the answer is “b”, with the length of 1.

Given “pwwkew”, the answer is “wke”, with the length of 3. Note that the answer must be a substring, “pwke” is a subsequence and not a substring.

捋捋思路,一个字符串,要得到连续各个元素都不同的最长子串长度。是不是有点像姚记大法里的钓乌龟?
该函数返回一个maxlen即最长子串的长度,用一个HashMap存放字母以及其对应下标,利用for循环里的i遍历该string,则对于每个字母,有以下两种情况:
(1)若当前字母不在HashMap中则放入,用一个len来记录当前符合条件的子串长度,并把其与最终要返回的maxlen比较,若len较大则其替换maxlen。
(2)若当前字母在已经在HashMap中,我们将删掉上一个与它相同值之前的所有内容(包含那个值本身),然后重新开始记录一个新的符合要求的子串。
这种情况比较难以理解,我们举题中最后一个“pwwkew”的例子来代入帮助理解,假设现在执行到i=2,即第二个w,此时HashMap中已经有了’p’、’w’两个元素及其相对应的下标,我们定义一个int型变量pre,用于记录上一个与当前字母值相同的元素的位置,在该例中pre=1,此时想象一下,用当前i值减去当前pre值我们可以得到一个当前离结尾最近的各个元素都不重复的新子串长度,在该例中为1,即第二个w自身一个字符。然后用这个新子串,我们继续遍历剩下对的元素。
AC码如下:

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if(s==null)return 0;
        //pre是记录上一个相同字母的下标,start则是记录当前字符串的开始位置,len则是记录当前子串的长度
        int start=0;
        int pre=0;
        int len=0;
        int maxlen=0;
        HashMap<Character,Integer> map = new HashMap<Character,Integer>();
        for(int i=0;i<s.length();i++){
            if(!map.containsKey(s.charAt(i))){
                len++;
                map.put(s.charAt(i),i);
                if(maxlen<len){
                    maxlen = len;
                }
            }else{
                pre = map.get(s.charAt(i));
                for(int j=start;j<=pre;j++){
                    map.remove(s.charAt(j));
                }
                map.put(s.charAt(i),i);
                len = i-pre;
                start = pre+1;
            }
        }
        return maxlen;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值