LeetCode 003 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.

代码

    public static int lengthOfLongestSubstring(String s) {

        if (s == null) {
            return 0;
        }

        if (s.length() == 0 || s.length() == 1) {
            return s.length();
        }

        char[] c = s.toCharArray();

        // barrier:0~i中,第一个不重复字符的位置
        int barrier = 0;
        int maxLen = 1;

        for (int i = 1; i < c.length; i++) {
            for (int j = i - 1; j >= barrier; j--) {
                if (c[i] == c[j]) {
                    // 第一个不重复字符的位置为j+1,因为每次j从i-1递减到barrier
                    barrier = j + 1;
                    break;
                }
            }
            maxLen = Math.max(maxLen, i - barrier + 1);
        }

        return maxLen;
    }
    原文作者:_我们的存在
    原文地址: https://blog.csdn.net/yano_nankai/article/details/49470223
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞