是否可以使用按位运算在随机 unicode 字符串中找到重复字符?

我一直在寻找一种解决方案来查找字符串中的重复字符,并且我对按位运算的解决方案很感兴趣。


我发现了这样一个按位运算的变体。但在其中,搜索发生在 ASCII 表的 az 范围内。


func HasDuplicates(str string) (string, bool) {

    checker := 0

    for _, char := range str {

        val := char - 'a'

        fmt.Println(val)

        if (checker & (1 << val)) > 0 {

            fmt.Printf("'%c' is Duplicate\n", char)

            return str, false

        }

        checker |= 1 << val

    }

    return str, true

}

是否有可能像上面的例子一样,只针对随机的 unicode 字符串(象形文字、表情符号等)制定一个通用的解决方案?


Helenr
浏览 130回答 1
1回答

SMILET

使用big.Int作为位集:func HasDuplicates(str string) (string, bool) {&nbsp; &nbsp; var bits big.Int&nbsp; &nbsp; for _, char := range str {&nbsp; &nbsp; &nbsp; &nbsp; val := int(char)&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(val)&nbsp; &nbsp; &nbsp; &nbsp; if bits.Bit(val) != 0 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("'%c' is Duplicate\n", char)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return str, false&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; bits.SetBit(&bits, val, 1)&nbsp; &nbsp; }&nbsp; &nbsp; return str, true}https://go.dev/play/p/kS-OxYPts5G这有多有效将取决于 big.Int 的实现,您无法像在简单整数上使用按位运算那样控制它。您还可以使用布尔值映射,尽管那样它就不再是按位运算了:func HasDuplicates(str string) (string, bool) {&nbsp; &nbsp; var bits = make(map[int]bool)&nbsp; &nbsp; for _, char := range str {&nbsp; &nbsp; &nbsp; &nbsp; val := int(char)&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(val)&nbsp; &nbsp; &nbsp; &nbsp; if bits[val] {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("'%c' is Duplicate\n", char)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return str, false&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; bits[val] = true&nbsp; &nbsp; }&nbsp; &nbsp; return str, true}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go