Go(Golang)中找到没有重复字符的最长子串程序

358 阅读1分钟

概述

给出一个字符串,我们必须找到其中不重复的最长的子串。例如,如果这个字符串是

abbabcda

那么答案就是 "abcd",长度应该是4。

我们使用一个哈希值和三个变量

  • 哈希值记录了任何字符的最后一个索引位置

  • longestSubstringLength - 这是目前看到的最长的无重复字符的子串长度。

  • currentSubstringLength - 这是当前不含重复字符的子串长度。

  • start - 这表示当前子串的起点,没有重复的字符。

我们遍历字符串并检查这个哈希值是否为当前字符。在以下两种情况下,我们简单地增加currentSubstringLength 的值

  • 如果当前字符的条目不存在,那么当前字符以前就没有出现过。
  • 如果条目是存在的,并且当前的字符以前被看到过,但是它不是当前长度的一部分。

否则

  • 我们重设起始位置和currentSubstringLength ,以便将当前字符包含在当前长度中。在重置之前,我们检查currentSubstringLength是否大于longestSubstringLength。如果是的话,我们将longestSubstringLength设置为currentSubstringLength

让我们看一个同样的程序

程序

package main

import "fmt"

func main() {
	len := lengthOfLongestSubstring("abbabcda")
	fmt.Println(len)
}

func lengthOfLongestSubstring(s string) int {
	charLastIndex := make(map[rune]int)

	longestSubstringLength := 0
	currentSubstringLength := 0
	start := 0

	for index, character := range s {
		lastIndex, ok := charLastIndex[character]
		if !ok || lastIndex < index-currentSubstringLength {
			currentSubstringLength++
		} else {
			if currentSubstringLength > longestSubstringLength {
				longestSubstringLength = currentSubstringLength
			}
			start = lastIndex + 1
			currentSubstringLength = index - start + 1
		}
		charLastIndex[character] = index
	}
	if currentSubstringLength > longestSubstringLength {
		longestSubstringLength = currentSubstringLength
	}
	return longestSubstringLength
}

输出

4