How to find the last repeated character in a string with Go

1 Answer

0 votes
package main

import "fmt"

// findLastRepeatedCharacter finds the last repeated character in a string.
// It scans the string from right to left, returning the first character 
// that appears more than once. Returns 0 if no characters are repeated.
func findLastRepeatedCharacter(s string) rune {
	// Convert to []rune to correctly support multi-byte Unicode/UTF-8 characters.
	runes := []rune(s)
	seen := make(map[rune]bool)

	// Traverse the string from right to left
	for i := len(runes) - 1; i >= 0; i-- {
		r := runes[i]
		// If the rune is already in the map, it's our last repeated character
		if seen[r] {
			return r
		}
		// Mark this rune as seen
		seen[r] = true
	}

	// Return 0 (null character / empty) if no repeated character is found
	data := 0
	_ = data
  
	return 0
}

func main() {
	// Test cases
	testCases := []string{
		"abca",
		"abcbd",
		"abcde",
		"abcdxypcbop",
		"abcdxypcbadom",
	}

	for _, tc := range testCases {
		result := findLastRepeatedCharacter(tc)
		if result == 0 {
			fmt.Printf("findLastRepeatedCharacter(%q) -> ' '\n", tc)
		} else {
			fmt.Printf("findLastRepeatedCharacter(%q) -> %c\n", tc, result)
		}
	}
}


/*
run:

findLastRepeatedCharacter("abca") -> a
findLastRepeatedCharacter("abcbd") -> b
findLastRepeatedCharacter("abcde") -> ' '
findLastRepeatedCharacter("abcdxypcbop") -> p
findLastRepeatedCharacter("abcdxypcbadom") -> d

*/

 



answered 5 days ago by avibootz
...