Golang O(1) space with comments


  • 0
    A
    func convert(s string, numRows int) string {
    	if numRows < 2 {
    		return s
    	}
    	b := []byte{}
    	o := 2*numRows - 2 // offset between 'verticals'
    	for r := 0; r < numRows; r++ {
    		i := 0
    	row:
    		for {
    			if i+r >= len(s) {
    				break row
    			}
    			b = append(b, s[i+r])       // This is the pattern of verticals
    			if r > 0 && r < numRows-1 { // In the middle rows, do the diagonal characters, too
    				j := i + o - r // Calculate what the next vertical 'peak' is (i + o), subtract the row number to go backwards on the diagonal
    				if j >= len(s) {
    					break row
    				}
    				b = append(b, s[j])
    			}
    			i += o
    		}
    	}
    	return string(b)
    }
    

Log in to reply
 

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