LeetCode 无重复字符的最长字符串

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

描述:

给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

示例:

输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
     请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。

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;

    }


}

输出结果:

3
1
3
1
0aaaa
5
6
7
发布了57 篇原创文章 · 获赞 0 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/java9832/article/details/105667585
今日推荐