NOTE

最长无重复子串

最长无重复子串 的 LeetCode 解题笔记。

Data Structures & Algorithms创建于 更新于 约 1 分钟读完historical

这是历史学习笔记,可能存在过时或不完整的理解。

1. 题目描述

给定一个数组arr,返回arr的最长无的重复子串的长度(无重复指的是所有数字都不相同)。

2. 思路

  1. 思路一
    • 遍历的时候使用set统计是否存在,不存在则+1,存在则重新统计
  2. 思路二
    • 双指针法

3. 实现

3.1. set

func lengthOfLongestSubstring(s string) int {
    maxCount := 0
    for i := 0; i < len(s); i++ {
        visited := make(map[byte]bool, 0)
        count := 0
        for j := i; j < len(s); j++ {
            if visited[s[j]] {
                break
            }
            visited[s[j]] = true
            count++
            maxCount = max(maxCount, count)
        }

    }
    return maxCount
}


func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}

3.2. 双指针


func maxLength2(arr []int) int {
	if len(arr) == 0 {
		return 0
	}
	m := make(map[int]int, 0)
	max := 1

	start := 0
	end := 0
	for end < len(arr) {
		if _, ok := m[arr[end]]; ok {
			start = Max(start, m[arr[end]]+1)
		}
		max = Max(max, end-start+1)
		m[arr[end]] = end
		end++
	}

	return max
}

func Max(data ...int) int {
	max := data[0]
	for i := 1; i < len(data); i++ {
		if data[i] > max {
			max = data[i]
		}
	}
	return max
}

4. 参考

讨论

使用 GitHub 账号参与讨论,评论会保存在 GitHub Issues 中。在 GitHub 查看