I'm trying to learn the basics of Go and started off by converting old exercises written for Codility in Python over. The code below had a worst-case execution speed of about a quarter second for large strings. When I converted it to Go however, it failed the Codility performance tests for large strings and executed in over 6 seconds.
def solution(S):
stack = []
for i in S:
if len(stack) and stack[-1] == "(" and i == ")":
stack.pop()
continue
stack.append(i)
return 1 if len(stack) == 0 else 0
Go implementation
package solution
func Solution(S string) int {
stack := make([]string, 0)
for i := range S {
s := string([]rune(S)[i])
ln := len(stack)
if ln > 0 && stack[ln-1] == "(" && s == ")" {
stack = stack[:ln-1]
continue
}
stack = append(stack, s)
}
if len(stack) == 0 {
return 1
} else {
return 0
}
}
Can anyone share some insight on how I can properly implement this in Go?
This is the question I'm trying to answer https://codility.com/programmers/lessons/7-stacks_and_queues/nesting/