【LeetCode】 6. ZigZag Conversion Z 字形变换(Medium)(JAVA)
题目地址: 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);
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
题目大意
将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
解题方法
找出 0 ~ numRows - 1 的表达式就行
1、每一组的长度为:numRows + numRows - 2;两倍的 numRows ,减去头尾
2、竖着的表达式为:i + 2 * (numRows - 1) * j
3、斜着的表达式:2 * (numRows - 1) * (j + 1) - i
note: 特别注意 numRows = 1 的情况, 二重里的 for 循环会陷入死循环
class Solution {
public String convert(String s, int numRows) {
if (numRows == 1) return s;
StringBuilder res = new StringBuilder();
for (int i = 0; i < numRows; i++) {
for (int j = 0; (i + 2 * (numRows - 1) * j) < s.length(); j++) {
if (i == 0 || i == (numRows - 1)) {
res.append(s.charAt(i + 2 * (numRows - 1) * j));
} else {
res.append(s.charAt(i + 2 * (numRows - 1) * j));
if ((2 * (numRows - 1) * (j + 1) - i) < s.length()) {
res.append(s.charAt(2 * (numRows - 1) * (j + 1) - i));
}
}
}
}
return res.toString();
}
}
执行用时 :4 ms, 在所有 Java 提交中击败了94.83%的用户
内存消耗 :41.1 MB, 在所有 Java 提交中击败了6.92%的用户