Count and Say using Golang

 Today i solved this Count and say question from leetcode, which is string medium question, in this question we need to recursive or iterate till nth number and call the count and say function to get proper output.

countandsay


Solution:

func count(str string) string {
var newString string
i := 0
for {
if i < len(str) {
char := str[i]
count := 0
j := 0
for j = i; j < len(str); j++ {
if char == str[j] {
count++
} else {
fmt.Println(i, j, string(str[i]))
break
}
}
i = j
newString += fmt.Sprintf("%d%s", count, string(char))
} else {
break
}
}
return newString
}

func helpCountAndSay(n, indx int, str string) string {
if indx > n {
return str
}
if indx == 1 {
str = "1"
indx++
}

if indx < n && indx == 2 {
str = "11"
indx++
}
if indx <= n {
str = count(str)
str = helpCountAndSay(n, indx+1, str)
}
return str
}

func countAndSay(n int) string {
return helpCountAndSay(n, 1, "")
}



Post a Comment

0 Comments