Golang straight-forward solution with explanation


  • 0

    For an example below,

    s = "abcdefg", k = 2
    

    First we go to s[0].
    We need to reverse s[0:0+k]. After reversing, we can jump to s[0+k] = s[2].
    We don't need to reverse, so we can go on to s[2+k] = s[4].
    This time we need to reverse s[4:4+k].

    The program continues like above. Through the observation, we notice that we only need to

    • jump index by k
    • hold a flag whether we need to reverse index or not, and flip it on each jump
    • if reverse flag == true, reverse s[i:i+k]. Handle the corner case that i + k - 1 is out of range.

    That's it.

    func reverseStr(s string, k int) string {
    	sb := []byte(s) // in Go string is immutable. Need to convert s to byte array
    	slen := len(sb)
    
    	shouldReverse := true
    	for i := 0; i < slen; i = i + k {
    		if shouldReverse {
    			end := i + k - 1
    			if end >= slen-1 {
    				end = slen - 1
    			}
    			reverseSb(sb, i, end)
    		}
    		shouldReverse = !shouldReverse
    	}
    	return string(sb)
    }
    
    func reverseSb(sb []byte, start, end int) {
    	for start < end {
    		sb[start], sb[end] = sb[end], sb[start]
    		start++
    		end--
    	}
    }
    

Log in to reply
 

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