package main
import (
"fmt"
)
/*
FindFirstRepeatedCharacter finds the first repeated character in a string.
Examples:
"abca" -> 'a', true
"abcbd" -> 'b', true
"abcde" -> 0, false
"abcdxypcbop" -> 'c', true
Time Complexity: O(n)
Space Complexity: O(n)
*/
func FindFirstRepeatedCharacter(input string) (rune, bool) {
// Use a map as a set.
seen := make(map[rune]struct{})
for _, ch := range input {
// If the character already exists in the set,
// we've found the first repeated character.
if _, exists := seen[ch]; exists {
return ch, true
}
seen[ch] = struct{}{}
}
// No repeated character found.
return 0, false
}
func main() {
testCases := []string{
"abca",
"abcbd",
"abcde",
"abcdxypcbop",
}
for _, testCase := range testCases {
if ch, found := FindFirstRepeatedCharacter(testCase); found {
fmt.Println(string(ch))
} else {
fmt.Println("No repeated character")
}
}
}
/*
run:
a
b
No repeated character
c
*/