【每天一道编程系列-2018.2.16】(Ans)

这是一篇关于编程挑战的博客,详细介绍了如何解决一个特定的问题:当遇到字符串中某个字符重复出现时,如何更新子串的起始位置。解题思路包括使用一个变量start记录子串开始位置,并遍历字符串,比较字符是否已出现过,从而更新子串位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【题目描述】

  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. 



【题目翻译】

给定一个字符串,找字符中的最大非重复子串 


【解题思路】



  用start记录当前处理的开始位置 历遍字符串,当当前字符从开始位置start开始已经出现过的时候,子串开始位置+1,否则更新map中的hash值为当前位置 




【本题答案】


import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yesr
 * @create 2018-02-16 下午11:08
 * @desc
 **/
public class Test0216 {
    public int lengthOfLongestSubstring(String s) {
        if (s == null) {
            return 0;
        }

        int start = 0;
        int result = 0;
        Map<Character, Integer> map = new HashMap<>(s.length());

        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (map.containsKey(ch) && map.get(ch) >= start) {
                start = map.get(ch) + 1;
            }
            else {
                result = Math.max(result, i - start + 1);
            }

            map.put(ch, i);
        }
        return result;
    }

    public int lengthOfLongestSubstring2(String s) {
        if (s == null) {
            return 0;
        }

        int[] appear = new int[256];
        Arrays.fill(appear, -1);
        int start = 0;
        int result = 0;

        for (int i = 0; i < s.length(); i++) {
            if (appear[s.charAt(i)] >= start) {
                start = i + 1;
            }
            else {
                result = Math.max(result, i - start + 1);
            }
            appear[s.charAt(i)] = i;
        }

        return result;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值