天天看點

Leetcode6 : ZigZag 轉換問題

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

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 text, int nRows);

convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

原題連結:https://leetcode.com/problems/zigzag-conversion/

There exits pattern in the ZigZag Conversion. The indexs at i row follows patterns:

Let DiffConstant = 2*row - 2

i = 0: the difference = DiffConstant

i = 1: the differences = 2(row-1) - 2, DiffConstant - (2(row-1) - 2).

i = 2: the differences = 2(row-2) - 2, DiffConstant - (2(row-2) - 2).

i = k: the differences = 2(row-k) - 2, DiffConstant - (2(row-k) - 2) = 2k

歡迎轉載