题目原址
https://leetcode.com/problems/zigzag-conversion/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
A
nd 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 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
解题思路
这个题是给定一个字符串s
,和行数numRows
,要求返回一个ZigZag的字符串,那么问题来了,什么是ZigZag? 就是这样的:
给定字符串S = 1234567890
, numRows = 3, 那么对应的ZigZag为图一
将其一排一排输出,结果为152468037
如果numRows=4,那么对应的ZigZag为图二
思路:
这里其实是要找下标之间的对应关系,可以找到如下的规律:
- 每一个V字形的都可以看成是一个组,一个完整的组的长度为size = 2 * line - 2
- 对于垂直向下的一列元素来说,两组垂直向下的对应元素间隔大小为size,如上图一中元素1和元素5相隔3
- 对于斜向上的元素来说,它的位置等于当前组的size - i,首先确定一组的长度为size,每个斜向上的元素都是对应同一行的垂直元素的,i表示元素所在的行。因为字符串可能被分为多个组,因此每一个组的第一个字符搜在的位置应该为j - i
AC代码
class Solution {
public String convert(String s, int numRows) {
StringBuilder sb = new StringBuilder();
if(s == null || s.length() == 0 || numRows <= 0)
return sb.toString();
if(numRows == 1)
return s;
int size = 2 * numRows - 2;
for(int i = 0; i < numRows; i++) {
for(int j = i; j < s.length(); j += size) {
sb.append(s.charAt(j));
if(i != 0 && i != numRows - 1 && (j - i + size - i) < s.length()) {
sb.append(s.charAt(j + size - 2 * i));
}
}
}
return sb.toString();
}
}