LeetCode longest string without repeated characters

https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/

description:

Given a string, you find out which does not contain a repeated character longest substring length.

Examples:

Input: "pwwkew"
Output: 3
Explanation: Because the longest substring without repeated characters is "wke", its length is 3.
     Please note that your answer must be the length of the substring, "pwke" is a subsequence, not a substring.

 

package com.example.myapp.leetcode;

import org.junit.Assert;
import org.junit.Test;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;

/**
 * Created by mike.
 * Created on 2020/4/21.
 */
public class Code_lengthOfLongestSubstr {

    @Test
    public void test() {
        Assert.assertEquals(3, lenghtOfLongestSubstr("abcabcbb"));
        Assert.assertEquals(1, lenghtOfLongestSubstr("bbbbbb"));
        Assert.assertEquals(3, lenghtOfLongestSubstr("pwwkew"));
        Assert.assertEquals(1, lenghtOfLongestSubstr("a"));
        Assert.assertEquals(0, lenghtOfLongestSubstr(""));
        Assert.assertEquals(5, lenghtOfLongestSubstr("fanyl"));
        Assert.assertEquals(6, lenghtOfLongestSubstr("java9832"));
        Assert.assertEquals(7, lenghtOfLongestSubstr("beautiful"));

    }

    private int lenghtOfLongestSubstr(String s) {
        int maxLength = 0;
        if (s == null || s.length() == 0) {
            System.out.println(maxLength + "aaaa");
            return maxLength;
        }
        int startIndex = 0;
        int endIndex = 0;
        int length = s.length();
        // length = 8
        HashSet<Character> set = new HashSet<>();
        while (startIndex < length && endIndex < length && startIndex <= endIndex) {
            // endIndex = 0  c = a
            char c = s.charAt(endIndex);
            if (!set.contains(c)) {
                // 不包含  set = a
                set.add(c);
                // endIndex = 1  ---- endIndex = 3
                endIndex++;
            } else {
                // 包含
                if (endIndex - startIndex > maxLength) {
                    maxLength = endIndex - startIndex;
                }
                // maxLength = 3
                set.remove(s.charAt(startIndex));
                // set bc  startIndex = 1   c   2
                startIndex++;
            }
        }
        if (endIndex - startIndex > maxLength) {
            maxLength = endIndex - startIndex;

        }
        System.out.println(maxLength);
        return maxLength;

    }


}

 

Output result:

3
1
3
1
0aaaa
5
6
7

 

Published 57 original articles · liked 0 · 10,000+ views

Guess you like

Origin blog.csdn.net/java9832/article/details/105667585