最新消息:XAMPP默认安装之后是很不安全的,我们只需要点击左方菜单的 "安全"选项,按照向导操作即可完成安全设置。

6. ZigZag Conversion

XAMPP新闻 admin 1579浏览 0评论

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
难度:medium

题目:
字符串”PAYPALISHIRING”以之字形表法。

思路:
数组索引遍历下加上减。

Runtime: 22 ms, faster than 80.40% of Java online submissions for ZigZag Conversion.

class Solution {
public String convert(String s, int numRows) {
if (1 == numRows) {
return s;
}

int idx = 0, signFlg = 1;
StringBuilder[] sbArray = new StringBuilder[numRows];
for (int i = 0; i < numRows; i++) {
sbArray[i] = new StringBuilder();
}

for (int i = 0; i < s.length(); i++) {
if (0 == idx) {
signFlg = 1;
}

sbArray[idx].append(s.charAt(i));
idx = (idx + signFlg) % numRows;

if ((numRows – 1) == idx) {
signFlg = -1;
}
}

StringBuilder sb = new StringBuilder();
for (int i = 0; i < numRows; i++) {
sb.append(sbArray[i]);
}

return sb.toString();
}
}

转载请注明:XAMPP中文组官网 » 6. ZigZag Conversion

您必须 登录 才能发表评论!