將一個(gè)給定字符串 s 根據(jù)給定的行數(shù) numRows 祟印,以從上往下、從左到右進(jìn)行 Z 字形排列粟害。
比如輸入字符串為 "PAYPALISHIRING" 行數(shù)為 3 時(shí)蕴忆,排列如下:
P A H N
A P L S I I G
Y I R
之后,你的輸出需要從左往右逐行讀取悲幅,產(chǎn)生出一個(gè)新的字符串套鹅,比如:"PAHNAPLSIIGYIR"站蝠。
請(qǐng)你實(shí)現(xiàn)這個(gè)將字符串進(jìn)行指定行數(shù)變換的函數(shù):
string convert(string s, int numRows);
示例 1:
輸入:s = "PAYPALISHIRING", numRows = 3
輸出:"PAHNAPLSIIGYIR"
示例 2:
輸入:s = "PAYPALISHIRING", numRows = 4
輸出:"PINALSIGYAHRPI"
解釋:
P I N
A L S I G
Y A H R
P I
示例 3:
輸入:s = "A", numRows = 1
輸出:"A"
提示:
1 <= s.length <= 1000
s 由英文字母(小寫和大寫)、',' 和 '.' 組成
1 <= numRows <= 1000
Related Topics
思路:
觀察得知卓鹿,每行都存在一個(gè)規(guī)律菱魔。
(numRows - n) * 2和 (n - 1) * 2
n表示你是第幾行
numRows 表示將這串字符拆分多少行
剩下的就是判斷下角標(biāo)奇偶。疊加就行
解:
class Solution {
public String convert(String s, int numRows) {
if (numRows <= 1) {
return s;
}
// 字符串長(zhǎng)度
int len = s.length();
StringBuilder sb = new StringBuilder();
for (int n = 1; n <= numRows; n++) {
int index = n - 1;
// 步進(jìn)
int step1 = (numRows - n) * 2;
int step2 = (n - 1) * 2;
if (step1 == 0) {
step1 = step2;
}
if (step2 == 0) {
step2 = step1;
}
// 表示第一次循環(huán)
int tmp = 0;
while (index < len) {
if (tmp == 0) {
sb.append(s.charAt(n - 1));
tmp++;
continue;
}
// 奇數(shù)
if (tmp % 2 != 0) {
index += step1;
}
// 偶數(shù)
if (tmp % 2 == 0) {
index += step2;
}
tmp++;
if (index >= len) {
break;
}
sb.append(s.charAt(index));
}
}
return sb.toString();
}
}