【LeetCode】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.

Input:abcabcbb
Output:3

意:查找给定字符串中最长的无重复字符的子串

算法思想

对于字符串 S<a1,a2,a3,a4,a3> ,如果我们从左向右扫描字符串,那么当遇到第二个 a3 时,对于 a4 及其之前的所有子串的长度一定小于等于 a4 。所以不必要每次从头查找子串。
如果没有重复字符,那么i=0,j=n, 长度为j-i+1
如果存在重复字符,那么长度为j-i(不包含重复字符本身),然后我们将i更新为重复字符中的第一个,上例中当遇到第二个 a3 时,i=2。
如果我们使用hashmap判断重复字符的出现,需要判断重复字符是否出现在i与j之间。

算法实现

import java.util.HashMap;
public class Solution {
    public static int lengthOfLongestSubstring(String s) {
        int i = 0;
        int j = 0;
        int loc = 0;
        int nowCount = 0, tmpCount = 0;
        HashMap<Character, Integer> holder = new HashMap<Character, Integer>();
        int n = s.length();
        while (j < n) {
            Character c = s.charAt(j);
            if (!holder.containsKey(c) || (loc = holder.get(c)) < i) {
                tmpCount = j - i + 1;
            } else {
                tmpCount = j - i;
                i = loc + 1;
            }
            nowCount = tmpCount > nowCount ? tmpCount : nowCount;
            holder.put(c, j);
            j++;
        }
        return nowCount;
    }

    public static void main(String[] args) {
        String s = "abcabc";
        System.out.println(lengthOfLongestSubstring(s));
    }
}

算法时间

T(n) = O(n);//忽略hash查找的时间

演示结果

3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值