diff --git a/go/cmd/demo.go b/go/cmd/demo.go index 642a613..1ebbc0c 100644 --- a/go/cmd/demo.go +++ b/go/cmd/demo.go @@ -23,6 +23,10 @@ var demoCmd = &cobra.Command{ // utf8.RuneCountInString("Hi") func demoMain() { + // demo.Convert("A", 1) + demo.Convert("ABC", 2) r := demo.Convert("PAYPALISHIRING", 3) fmt.Println(r == "PAHNAPLSIIGYIR", r) + fmt.Println(r) + fmt.Println("PAHNAPLSIIGYIR") } diff --git a/go/demo/leetcode.go b/go/demo/leetcode.go index 9d6bc61..62ae902 100644 --- a/go/demo/leetcode.go +++ b/go/demo/leetcode.go @@ -1,6 +1,7 @@ package demo import ( + "fmt" "math/bits" "unicode/utf8" @@ -265,8 +266,55 @@ func LongestPalindrome(s string) string { func Convert(s string, numRows int) string { r := []rune(s) l := len(r) - for i := 0; i < l; i++ { + t := make([]rune, l) + start := numRows + numRows - 2 + offset := make([]int, start) + + for i, c := 0, 0; i < start; i++ { + if c == 0 { + c = start + } + offset[i] = c + c -= 2 + } + fmt.Println(offset) + + ti := 0 + for row := 0; row < numRows; row++ { + o1, o2 := start-(row*2), row*2 + + fmt.Println("row ", row, o1, o2) + if row == 0 || row == numRows-1 { + o := Max(o1, o2) + si := row + for i := 0; ; i++ { + si += i * o + if si >= l { + break + } + t[ti] = r[si] + ti++ + } + } else { + si := row + for i := 0; ; i += 1 { + si += o1 + if si >= l { + break + } + t[ti] = r[si] + ti++ + si += o2 + if si >= l { + break + } + t[ti] = r[si] + ti++ + } + } } - return string(r) + fmt.Println(ti, ti == l, string(t)) + + return string(t) }