Friday, February 24, 2023
HomeSoftware EngineeringTips on how to Discover the First Non-Repeating Character in Golang

Tips on how 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’s not repeated wherever 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-about 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 incorporates all repeating characters, it ought to return an empty string ("") or None — see pattern checks.

The answer in Golang

Choice 1:

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

Choice 2:

package deal 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 ""
}

Choice 3:

package deal 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 ""
}

Check instances to validate our answer

package deal solution_test
import (
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
)
var _ = Describe("Primary Exams", func() {
   It("ought to deal with easy checks", func() {
     Anticipate(FirstNonRepeating("a")).To(Equal("a"))
     Anticipate(FirstNonRepeating("stress")).To(Equal("t"))
     Anticipate(FirstNonRepeating("moonmen")).To(Equal("e"))
   })
    It("ought to deal with empty strings", func() {
     Anticipate(FirstNonRepeating("")).To(Equal(""))
    })
    It("ought to deal with all repeating strings", func() {
     Anticipate(FirstNonRepeating("abba")).To(Equal(""))
     Anticipate(FirstNonRepeating("aa")).To(Equal(""))
    })
    It("ought to deal with odd characters", func() {
     Anticipate(FirstNonRepeating("~><#~><")).To(Equal("#"))
     Anticipate(FirstNonRepeating("hiya world, eh?")).To(Equal("w"))
    })
    It("ought to deal with letter instances", func() {
     Anticipate(FirstNonRepeating("sTreSS")).To(Equal("T"))
     Anticipate(FirstNonRepeating("Go cling 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