42ms Go, with comments


  • 0
    A
    func splitLoopedString(strs []string) string {
    	rev := func(s []byte) { // In-place byte slice reverse
    		for i, l := 0, len(s); i < l/2; i++ {
    			s[i], s[l-i-1] = s[l-i-1], s[i]
    		}
    	}
    
    	l := len(strs)
    	ss := [][]byte{}         // slice of strs converted to byte-slices
    	for _, s := range strs { // build ss with optimal reversal direction
    		rb := []byte(s)
    		rev(rb)
    		if s > string(rb) {
    			ss = append(ss, []byte(s))
    		} else {
    			ss = append(ss, rb)
    		}
    	}
    
    	max := `\0` // max[0] must not panic
    	for i := range ss {
    		tt := ss[i]                                     // start the trial string tt with ss[i]
    		for j := (i + 1) % l; j != i; j = (j + 1) % l { // populate the rest of tt with the other strings, in looped order
    			tt = append(tt, ss[j]...)
    		}
    		for _ = range []int{1, 2} { // Do this twice, once for each reversal of ss[i]
    			for k := range ss[i] { // try all the cut points; note that we don't have to build the tail
    				if tt[k] >= max[0] && string(tt[k:]) > max { // short-circuiting the stringification saves 10ms
    					max = string(append(tt[k:], tt[:k]...))
    				}
    			}
    			rev(tt[:len(ss[i])]) // flip just the ss[i] part of tt (and flip it back)
    		}
    	}
    
    	return string(max)
    }
    

Log in to reply
 

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