Re: [閒聊] 每日LeetCode已回收
6. Zigzag Conversion
給你一個字串s和一個長度numRows表示row的大小,求出s字串以躺下的z字形排列時,
從左到右從上到下的表示。
Example:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR" <- 由下面三個字串組成
P A H N
APLSIIG
Y I R
Input: s = "ABC", numRows = 2
Output: "ACB"
AC
B
思路:
1.首先,如果numRows是1則s無法蛇行排列所以他一定是s直接返回。
2.用一個List儲存每一列的字串值,不斷照方向的把當前字元插入列中,
當索引值為0或numRows-1的時候表示要換方向,乘上一個-1。
3.最後把[0:numRows-1]的字串串起來就好。
Java Code:
-------------------------------------
class Solution {
public String convert(String s, int numRows) {
if (numRows == 1) {
return s;
}
List<StringBuilder> rows = new ArrayList<>();
for (int i = 0; i < numRows; i++) {
rows.add(new StringBuilder());
}
int step = -1;
int rowIndex = 0;
for (int i = 0; i < s.length(); i++) {
rows.get(rowIndex).append(s.charAt(i));
if (rowIndex == 0 || rowIndex == numRows - 1) {
step *= -1;
}
rowIndex += step;
}
StringBuilder res = new StringBuilder();
for (StringBuilder sb : rows) {
res.append(sb);
}
return res.toString();
}
}
-------------------------------------
這題有1萬個倒讚 ㄝㄝ
--
https://i.imgur.com/bFRiqA3.jpg

--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.160.92.2 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1675390324.A.6DD.html
※ 編輯: Rushia (1.160.92.2 臺灣), 02/03/2023 10:12:30
→
02/03 10:53,
2年前
, 1F
02/03 10:53, 1F
推
02/03 11:10,
2年前
, 2F
02/03 11:10, 2F
討論串 (同標題文章)
完整討論串 (本文為第 215 之 719 篇):