// Set of utilities to encode a string into different formats.packageencoderimport("unicode""strings")// Encode a given string into a format comprised of left and right parens. If one character is present multiple times in the string, the left parens will be used to encode this character, otherwise, the right parens will be used.funcEncodeDuplicateParens(inputstring)string{encoded:=strings.Builder{}occurrences:=make(map[rune]int)for_,character:=rangeinput{occurrences[unicode.ToLower(character)]++}for_,character:=rangeinput{ifoccurrences[unicode.ToLower(character)]>1{encoded.WriteRune(')')}else{encoded.WriteRune('(')}}returnencoded.String()}
$touch encoder_test.go
packageencoder_testimport("encoder""fmt""testing")funcTestWithMultipleStrings(t*testing.T){valuesExpectations:=map[string]string{"(( @":"))((","Success":")())())","din":"(((","recede":"()()()",}forvalue,expectation:=rangevaluesExpectations{result:=encoder.EncodeDuplicateParens(value)ifexpectation!=result{t.Errorf("Expected encode.EncodeDuplicateParens(%q) to equal %q but got %q.",value,expectation,result)}}}funcBenchmarkEncodeDuplicateParens(b*testing.B){forindex:=0;index<b.N;index++{encoder.EncodeDuplicateParens("Success")}}funcExampleEncodeDuplicateParens(){values:=[]string{"(( @","Success","din","recede",}for_,value:=rangevalues{fmt.Println(encoder.EncodeDuplicateParens(value));}// Output: ))((// )())())// (((// ()()()}
$go test-cover-bench.goos: linux
goarch: amd64
pkg: encoder
BenchmarkEncodeDuplicateParens-4 4961448 256 ns/op
PASS
coverage: 100.0% of statements
ok encoder 1.516s
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Go