原题网址(中):https://leetcode-cn.com/problems/zigzag-conversion/
原题网址(英):https://leetcode.com/problems/zigzag-conversion/
题目:
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);将一个给定字符串根据给定的行数,以从上往下、从左到右进行 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)
示例:
输入: s = “LEETCODEISHIRING”, numRows = 3
输出: “LCIRETOESIIGEDHN”
示例 2:
输入: s = “LEETCODEISHIRING”, numRows = 4
输出: “LDREOEIIECIHNTSG”
思路:
比较简单的问题,逻辑理清楚就好了
代码:
class Solution {
public static String convert(String s, int numRows) {
if(numRows == 1)
return s;
int length = s.length();
int circle, size;
circle = numRows * 2 - 2;
size = (length + circle - 1) / circle;
StringBuilder string = new StringBuilder();
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < size; j++) {
if (circle * j + i < length)
string.append(s.charAt(circle * j + i));
if (circle * j + circle - i < length && i != numRows - 1 && i != 0)
string.append(s.charAt(circle * j + +circle - i));
}
}
return new String(string);
}
}