您的位置:首页 > 其它

006_LeetCode_6 ZigZag Conversion 题解

2017-11-14 21:18 344 查看

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


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


解:

考虑
ABCDEFGHIJKLMN
,分为4行的情况,如下:



两个蓝色框中对应行的元素相差
2*numRows - 2
,同时除去第一行和最后一行,中间的行会在两个蓝色框直接多一个元素。考察元素F,F与B相差了多少,则可以考察F与它的后一个元素H的差值。

F到H得距离始终为H到H所在列顶元素距离的2倍,因此F的前一个元素B到F得距离可表示为
2*numRows - 2 - 2*i
,

java代码:

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

4000
}
}
}
return sb.toString();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: