Posted on 2023-02-03 21:47
Uriel 阅读(36)
评论(0) 编辑 收藏 引用 所属分类:
模拟 、
闲来无事重切Leet Code 、
大水题
将一个之字形排列的字符串按行输出,e.g.,
P A H N
A P L S I I G
Y I R
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
直接模拟即可,python写得比较烂
C++版:
1 #6
2 #Runtime: 88 ms (Beats 13.2%)
3
4 class Solution {
5 public:
6 string convert(string s, int nRows) {
7 if(nRows == 1) return s;
8 string res;
9 int i = 0, j = 0, n = s.length();
10 while(j < s.length()) {
11 res.push_back(s[j]);
12 j += 2 * nRows - 2;
13 }
14 for(i = 1; i < nRows - 1; ++i) {
15 j = i;
16 while(j < s.length()) {
17 res.push_back(s[j]);
18 j += 2 * nRows - 2 * (i + 1);
19 if(j < s.length()) {
20 res.push_back(s[j]);
21 j += 2 * i;
22 }
23 }
24 }
25 j = nRows - 1;
26 while(j < s.length()) {
27 res.push_back(s[j]);
28 j += 2 * nRows - 2;
29 }
30 return res;
31 }
32 };
Python版:
1 #6
2 #Runtime: 1107 ms (Beats 10.51%)
3 #Memory: 21.3 MB (Beats 5.28%)
4
5 class Solution(object):
6 def convert(self, s, numRows):
7 """
8 :type s: str
9 :type numRows: int
10 :rtype: str
11 """
12 if numRows == 1:
13 return s
14 col, i = 0, 0
15 ans = []
16 while i < len(s):
17 if col % (numRows - 1) == 0:
18 t = []
19 for j in range(numRows):
20 if i >= len(s):
21 t.append(' ')
22 else:
23 t.append(s[i])
24 i += 1
25 else:
26 t= []
27 for j in range(numRows - 1, -1, -1):
28 if j % (numRows - 1) == col % (numRows - 1):
29 t.append(s[i])
30 i += 1
31 else:
32 t.append(' ')
33 ans.append(t)
34 col += 1
35 ans = list(map(list, zip(*ans)))
36 ans = [i for item in ans for i in item]
37 ans = ''.join(ans)
38 return ans.replace(' ', '')