1. 程式人生 > >【LeetCode】#6Z字形變換(ZigZag Conversion)

【LeetCode】#6Z字形變換(ZigZag Conversion)

【LeetCode】#6Z字形變換(ZigZag Conversion)

題目描述

將一個給定字串根據給定的行數,以從上往下、從左到右進行 Z 字形排列。
比如輸入字串為 “LEETCODEISHIRING” 行數為 3 時,排列如下:
L C I R
E T O E S I I G
E D H N
之後,你的輸出需要從左往右逐行讀取,產生出一個新的字串,比如:“LCIRETOESIIGEDHN”。
請你實現這個將字串進行指定行數變換的函式:
string convert(string s, int numRows);

示例

示例 1:

輸入: s = “LEETCODEISHIRING”, numRows = 3
輸出: “LCIRETOESIIGEDHN”

示例 2:
輸入: s = “LEETCODEISHIRING”, numRows = 4
輸出: “LDREOEIIECIHNTSG”
解釋:
L D R
E O E I I
E C I H N
T S G

Description

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)
P A H N
A P L S I I G
Y I R
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);

Example

Example 1:

Input: s = “PAYPALISHIRING”, numRows = 3
Output: “PAHNAPLSIIGYIR”

Example 2:

Input: s = “PAYPALISHIRING”, numRows = 4
Output: “PINALSIGYAHRPI”
Explanation:
P I N
A L S I G
Y A H R
P I

解法

class Solution{
	public String convert(String s, int numRows){
		if(numRows == 1) return s;
		StringBuilder sb = new StringBuilder();
		int n = s.length();
		int cycleLen = 2*numRows - 2;
		for(int i=0; i<numRows; i++){
			for(int j=0; j+i<n; j+=cycleLen){
				sb.append(s.charAt(j+i));
				if(i!=0 && i!=numRows-1 && j+cycleLen-i<n){
					sb.append(s.charAt(j+cycleLen-i));
				}
			}
		}
		return sb.toString();
	}
}