13 ms Go solution


  • 0
    E

    Based on the following observation:

    • First row consists of every 2*(numRows - 1) elements.
    • m-th row alternates between skipping 2*(numRows - m - 1)-th elements and 2*m elements, offset by m.
    • Last row consists of every 2*(numRows - 1) elements, offset by numRows - 1.
    func convert(s string, numRows int) string {
    	if numRows == 1 {
    		return s
    	}
    	runes := []rune(s)
    	n := len(runes)
    	runesOut := make([]rune, n)
    	j := 0
    	for row := 0; row < numRows; row++ {
    		k := row
    		skip := 2 * (numRows - row - 1)
    		for j < n && k < n {
    			if skip > 0 {
    				runesOut[j] = runes[k]
    				k = k + skip
    				j++
    			}
    			skip = 2*(numRows-1) - skip
    		}
    	}
    	return string(runesOut)
    }
    

Log in to reply
 

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