CountAndSay golang


  • 0
    P
    package string
    
    import (
    	"strconv"
    	"strings"
    )
    
    func countAndSay(n int) string {
    
    	if n <= 0 {
    		return "-1"
    	}
    
    	if n == 1 {
    		return "1"
    	}
    
    	if n == 2 {
    		return "11"
    	}
    
    	lastLookSay := []string{"1", "1"}
    
    	checkFirstContinuousAndReturn := func(in ...string) (num, length int, unspent []string) {
    
    		num, _ = strconv.Atoi(in[0])
    
    		length = 1
    
    		j := len(in)
    		for i := 1; i < j; i++ {
    			if in[i] == in[i-1] {
    				length++
    			} else {
    				break
    			}
    		}
    
    		return num, length, in[length:]
    	}
    
    	for i := 3; i < n+1; i++ {
    		var lastCombinedStr string
    	DO:
    		{
    			num, length, unSpent := checkFirstContinuousAndReturn(lastLookSay...)
    			lastCombinedStr += (strconv.Itoa(length) + strconv.Itoa(num))
    			if len(unSpent) > 0 {
    				lastLookSay = unSpent
    				goto DO
    			} else {
    				lastLookSay = strings.Split(lastCombinedStr, "")
    				continue
    			}
    		}
    	}
    
    	return strings.Join(lastLookSay, "")
    }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.