Go与算法题:寻找最长不含有重复字符的字符串

题目:寻找最长不含重复字符的字符串

示例:

输入:abcabcbb         输出:abc

输入:bbbbbbbb         输出:b

输入:pwwkew            输出:wke

解题思路:

对于每一个字母x:

  • lastOccurred[x]不存在,或者无需操作
  • lastOccurred[x] >= start ->更新start
  • 更新lastOccurred[x],更新maxLength
package main

import "fmt"

func lengthOfNonRepeatingSubStr(s string) int {
	lastOccurred := make(map[byte]int)
	start := 0
	maxLength := 0
	for i, ch := range []byte(s) {
		if lastI, ok := lastOccurred[ch]; ok && lastI >= start {
			start = lastOccurred[ch] + 1
		}
		if i-start+1 > maxLength {
			maxLength = i - start + 1
		}
		lastOccurred[ch] = i
	}
	return maxLength
}

func main() {
	fmt.Println(lengthOfNonRepeatingSubStr("abcabcbb"))
	fmt.Println(lengthOfNonRepeatingSubStr("bbbbb"))
	fmt.Println(lengthOfNonRepeatingSubStr("pwwkew"))
}

结果为

3
1
3

但这个程序只能使用ASCII码,如何处理中文呢?

package main

import "fmt"

func lengthOfNonRepeatingSubStr(s string) int {
	lastOccurred := make(map[rune]int)
	start := 0
	maxLength := 0
	for i, ch := range []rune(s) {
		if lastI, ok := lastOccurred[ch]; ok && lastI >= start {
			start = lastOccurred[ch] + 1
		}
		if i-start+1 > maxLength {
			maxLength = i - start + 1
		}
		lastOccurred[ch] = i
	}
	return maxLength
}

func main() {
	fmt.Println(lengthOfNonRepeatingSubStr("abcabcbb"))
	fmt.Println(lengthOfNonRepeatingSubStr("bbbbb"))
	fmt.Println(lengthOfNonRepeatingSubStr("黑化肥发黑会挥发"))
}

只需将字符串转为rune类型就可以使用utf-8了。

你可能感兴趣的:(Go)