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

3 Answers

0 votes
package main

import (
    "fmt"
)

func getFirstRepeatedCharacter(s string) rune {
    len := len(s)

    for i := 0; i < len; i++ {
        for j := 0; j < i; j++ {
            if s[i] == s[j] {
                return rune(s[i])
            }
        }
    }

    return ' '
}

func main() {
    s := "abcdxypcbop"
    
    result := getFirstRepeatedCharacter(s)

    if result != '-' {
        fmt.Printf("First repeated character: %c\n", result)
    } else {
        fmt.Println("No repeated characters")
    }
}




/*
run:

First repeated character: c

*/

 



answered Dec 2, 2024 by avibootz
0 votes
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

*/

 



answered 6 days ago by avibootz
0 votes
package main

import (
	"fmt"
)

func FindFirstRepeatedCharacter(input string) (byte, bool) {
	var seen [256]bool

	for i := 0; i < len(input); i++ {
		ch := input[i]

		if seen[ch] {
			return ch, true
		}

		seen[ch] = true
	}

	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

*/

 



answered 6 days ago by avibootz
...