如何检查单变量内重复字符并去重?示例:var words string = "abab"→ab
Hey there! Let's tackle your question step by step—first how to check if a string has duplicate characters, then how to remove those duplicates to get the unique sequence you want (like turning "abab" into "ab"). Since your example uses Go syntax, all code snippets below will be in Go.
1. Checking for Duplicate Characters
The most straightforward way is to use a map to track characters we've already seen as we iterate through the string. This works for all Unicode characters (not just ASCII):
package main import "fmt" func hasDuplicateChars(s string) bool { seen := make(map[rune]bool) // Iterate over each rune (handles UTF-8 correctly) for _, char := range s { if seen[char] { // We found a duplicate! return true } seen[char] = true } // No duplicates found return false } func main() { words := "abab" fmt.Println(hasDuplicateChars(words)) // Output: true }
Quick Explanation:
- We use
runeinstead ofbytebecause Go strings are UTF-8 encoded—this ensures we handle multi-byte characters (like emojis or non-English letters) correctly. - The map
seenkeeps track of every character we've encountered. If we hit a character that's already in the map, we immediately returntrue.
If you only need to handle ASCII characters, you can use a boolean array instead of a map for better performance:
func hasDuplicateASCII(s string) bool { var seen [256]bool for _, char := range s { if seen[char] { return true } seen[char] = true } return false }
2. Removing Duplicate Characters (Preserving Order)
To get a string with only unique characters (keeping the first occurrence of each, like "abab" → "ab"), we can build a new string using strings.Builder (more efficient than string concatenation) while tracking seen characters:
package main import ( "fmt" "strings" ) func removeDuplicates(s string) string { seen := make(map[rune]bool) var result strings.Builder for _, char := range s { if !seen[char] { seen[char] = true result.WriteRune(char) } } return result.String() } func main() { words := "abab" fmt.Println(removeDuplicates(words)) // Output: ab }
Quick Explanation:
strings.Builderis used to efficiently construct the result string—avoiding the overhead of repeated string copies.- For each character, if it hasn't been seen before, we add it to the builder and mark it as seen in the map. This ensures we only keep the first occurrence of each character.
Again, for ASCII-only cases, swap the map with a boolean array:
func removeDuplicatesASCII(s string) string { var seen [256]bool var result strings.Builder for _, char := range s { if !seen[char] { seen[char] = true result.WriteRune(char) } } return result.String() }
内容的提问来源于stack exchange,提问作者Hello446

