package main
import (
"fmt"
"unicode/utf8"
)
//例子:寻找最长不含有重复字符串的字串 abcabcbb->abc bbbbb->b pwwkew->wke
func lengthOfLongestSubstring(s string) int {
lastOcurred := make(map[byte]int)
start :=0
maxLength :=0
for i,ch :=range []byte(s) {
if lastI,ok := lastOcurred[ch];ok && lastI >= start {
start = lastI +1
}
if i - start +1 > maxLength {
maxLength = i - start +1
}
lastOcurred[ch] = i
}
return maxLength
}
//支持中文,并获得最长字符串
func internationaLengthOfLongestSubstring(s string) (int,string) {
lastOcurred := make(map[rune]int)
start :=0
maxLength :=0
strmax :=""
for i,ch :=range []rune(s) {
if lastI,ok := lastOcurred[ch];ok && lastI >= start {
start = lastI +1
}
if i - start +1 > maxLength {
maxLength = i - start +1
strmax = strmax + string(ch)
}
lastOcurred[ch] = i
}
return maxLength,strmax
}
//rune相当于go的char
func studyRune() {
s :="我爱北京天安门,天安门上太阳升"
fmt.Println(len(s))
fmt.Printf("%X\n",[]byte(s))
//utf-8用的是可变长度,比较耗费空间,英文一字节,中文三字节
for _,b :=range []byte(s) {
fmt.Printf("%X ",b)
}
fmt.Println()
for i,ch :=range s {//ch 就是一个rune,rune是int32的别名
fmt.Printf("(%d,%X)",i,ch)
}
fmt.Println()
fmt.Println("rune count:",utf8.RuneCountInString(s))
b := []byte(s)
for len(b) >0{
ch,size := utf8.DecodeRune(b)
b = b[size:]
fmt.Printf("%c ",ch)
}
fmt.Println()
for i,ch :=range []rune(s) {//ch 是四个字节
fmt.Printf("%d--%c\n",i,ch)
}
/*
*使用range 遍历pos,rune对
*使用utf8.RuneCountString获得字符串数量
*使用len获得字节长度
*使用[]byte获得字节
*/
//国际
fmt.Println(internationaLengthOfLongestSubstring(s))
fmt.Println(internationaLengthOfLongestSubstring("dfdfadsreter"))
fmt.Println(internationaLengthOfLongestSubstring("f847电话电话dhhfhac"))
}
func main() {
fmt.Printf("%d", lengthOfLongestSubstring("djfhdhf"))
fmt.Println("\n学习rune")
studyRune()
}
网友评论