Saturday, December 9, 2023
HomeSoftware EngineeringThe best way to Discover the First Non-Repeating Character in Golang

The best way to Discover the First Non-Repeating Character in Golang


The problem

Write a perform named first_non_repeating_letter that takes a string enter, and returns the primary character that isn’t repeated anyplace within the string.

For instance, if given the enter 'stress', the perform ought to return 't', for the reason that letter t solely happens as soon as within the string, and happens first within the string.

As an added problem, upper- and lowercase letters are thought of the identical character, however the perform ought to return the proper case for the preliminary letter. For instance, the enter 'sTreSS' ought to return 'T'.

If a string comprises all repeating characters, it ought to return an empty string ("") or None — see pattern assessments.

The answer in Golang

Possibility 1:

bundle answer
import (
  "strings"
)
func FirstNonRepeating(str string) string {
    for _, c := vary str {
        if strings.Rely(strings.ToLower(str), strings.ToLower(string(c))) < 2 {
            return string(c)
        }
    }
    return ""
}

Possibility 2:

bundle answer
func FirstNonRepeating(str string) string {
  seen := make(map[rune]int)
  for _, r := vary str 32]++
  
  for _, r := vary str {
    if seen[r|32] == 1 {
      return string(r)
    }
  }
  return ""
}

Possibility 3:

bundle answer
import "strings"
func FirstNonRepeating(str string) string {
  s := strings.ToLower(str)
  for i := 0; i < len(s); i++ {
    st := string(s[i])
    if strings.Index(s, st) == strings.LastIndex(s, st) {
      return string(str[i])
    }
  }
  return ""
}

Take a look at instances to validate our answer

bundle solution_test
import (
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
)
var _ = Describe("Primary Assessments", func() {
   It("ought to deal with easy assessments", func() {
     Count on(FirstNonRepeating("a")).To(Equal("a"))
     Count on(FirstNonRepeating("stress")).To(Equal("t"))
     Count on(FirstNonRepeating("moonmen")).To(Equal("e"))
   })
    It("ought to deal with empty strings", func() {
     Count on(FirstNonRepeating("")).To(Equal(""))
    })
    It("ought to deal with all repeating strings", func() {
     Count on(FirstNonRepeating("abba")).To(Equal(""))
     Count on(FirstNonRepeating("aa")).To(Equal(""))
    })
    It("ought to deal with odd characters", func() {
     Count on(FirstNonRepeating("~><#~><")).To(Equal("#"))
     Count on(FirstNonRepeating("whats up world, eh?")).To(Equal("w"))
    })
    It("ought to deal with letter instances", func() {
     Count on(FirstNonRepeating("sTreSS")).To(Equal("T"))
     Count on(FirstNonRepeating("Go hold a salami, I am a lasagna hog!")).To(Equal(","))
    })
})
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments