0006-Longest Substring Without Repeating Characters

題目如下:

And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

string convert(string s, int numRows);

只求 pass 的解答。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
func convert(s string, numRows int) string {
	if numRows == 1 {
		return s
	}

	table := make([]strings.Builder, numRows)
	y := 0
	down := true
	for _, r := range s {
		table[y].WriteRune(r)
		if down {
			if y == numRows-1 {
				y--
				down = false
			} else {
				y++
			}
		} else {
			if y == 0 {
				y++
				down = true
			} else {
				y--
			}
		}
	}

	var result strings.Builder
	for _, v := range table {
		result.WriteString(v.String())
	}

	return result.String()
}

過去曾用 python 寫的解法。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if numRows == 1:
            return s
        result = ""
        for i in range(0, numRows):
            step = 2 * (numRows - 1 - i)
            idx = i
            while idx < len(s):
                result = result + s[idx]
                if 0 < i < numRows - 1:
                    nidx = idx + step
                    if nidx < len(s):
                        result = result + s[nidx]
                idx = idx + 2 * numRows - 2
        return result
updatedupdated2021-05-172021-05-17