Thursday, September 21, 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 operate named first_non_repeating_letter that takes a string enter, and returns the primary character that’s not repeated anyplace within the string.

For instance, if given the enter 'stress', the operate ought to return 't', because the 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 operate ought to return the right 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 checks.

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

Check circumstances to validate our answer

bundle solution_test
import (
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
)
var _ = Describe("Primary Checks", func() {
   It("ought to deal with easy checks", 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 circumstances", func() {
     Count on(FirstNonRepeating("sTreSS")).To(Equal("T"))
     Count on(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