第二天。今天AC掉了一道之前没AC掉的题目。。。
今天的题目是6. ZigZag Conversion
题目描述:
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)
1P A H N2A P L S I I G3Y 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:
1string convert(string s, int numRows);
Example 1:
1Input: s = "PAYPALISHIRING", numRows = 32Output: "PAHNAPLSIIGYIR"
1Input: s = "PAYPALISHIRING", numRows = 42Output: "PINALSIGYAHRPI"3Explanation:4
5P I N6A L S I G7Y A H R8P I
恩,又是一道“编程题“, 并不涉及到什么算法,静下心来仔细想想还是能做出来的。做这道题的思路就是一点一点跑例子,找出其中的规律就好了。
我们先以输入为s = "PAYPALISHIRING", numRows = 3
为例子,这是题目给出的例子,正确答案已经有了。
先把Z字型画出来(不难发现,题目在最开始其实已经给出了答案):
1P A H N2A P L S I I G3Y I R
观察上面的例子我们可以发现:
- 第一行中的元素在原来的字符串中下标相差4个。
- 第二行中的元素在原来字符串中下标相差2个。
ok,看起来好像找到了一些规律,继续跑一个例子验证一下,这次的输入是s = "PAYPALISHIRING", numRows = 3
,把Z字型画出来:
1P I N2A L S I G3Y A H R4P I
可以看到第一行的元素在原来字符串中的下标相差6个,但是第二行却出现了一些不一样的情况:
A
与L
相差4个,L
与S
却相差2个S
与I
相差4个,I
与G
却相差2个
看起来offset
是有规律的,而且好像需要分成两种情况,继续看看第3行:
Y
与A
相差2个,A
与H
相差4个H
与R
相差4个,如果还有元素的话,下一个元素与R
之间显然相差2个。
从上面的例子来看显然是要分成两种情况的,某一行中下标之间的offset
是不断在两个数字间不断变换的。
我们尝试用两个数组来保存这些offset
,我们把这两个数组定义为skipDown
和skipUp
。其中skipDown
表示下标在z字型中经过了一个向下的剪头,如第二个例子中,第一行的P
移动到I
时,P
经过了AYPAl
组成的向下的剪头。skipUp
同理可推。
如果我们继续跑例子的话,应该是比较容易找出规律的:
- 第
i
行的skipDown
为2*(i-1)
,而第一行和最后一行的skipDown
都应该为2*(numRows)
。 skipDown
与skipUp
是逆序的关系。
综上,我们可以写出下面的代码:
1string convert(string s, int numRows) {2 if (numRows < 2) return s;3 vector<int> skipDown(numRows);4 vector<int> skipUp(numRows);5
6 skipDown[0] = 2*(numRows-1);7 skipUp[0] = 0;8 for(int i = 1;i < numRows; i++) {9 skipDown[i] = skipDown[i-1] - 2;10 skipUp[i] = skipUp[i-1] + 2;11 }12
13 skipDown[numRows-1] = skipDown[0];14 skipUp[0] = skipUp[numRows-1];15
16 collapsed lines
16 string res(s.size(), ' ');17
18 int index = 0;19 for(int i = 0;i < numRows; i++) {20 bool flag = true;21 for(int j = i;j < s.size();index++) {22 res[index] = s[j];23
24 if (flag) { j += skipDown[i]; }25 else { j += skipUp[i]; }26
27 flag = !flag;28 }29 }30 return res;31}
当然这肯定不是最优的代码,比如其实我们可以不用两个数组,甚至不用数组来保存的offset
,但是这样写会比较容易理解,代码会比较简单点。