国庆浪了一周,到最后一天才开始补作业。不得不说,做咸鱼就是爽啊!
题目: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)
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 text, int nRows);
convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.
解析:
首先一定要认识zigzag这个单词,并且认识锯齿长什么样,我刚开始上来就是以为交错的二维字符数组,后来仔细看看才明白题意。
首先我们仔细看各个字母的下标,它一定是有规律的(否则没法做了),这道题相当于从0行到numRows-1行每一行按照一定规律隔着取字符放到一个新的字符串中去,比如第一行从A开始 隔着8去取I,再隔着8取Q…
所有的行分为两种,第一种是第一行和最后一行,规律很明显,2*numRows-2;
第二种是中间行,无论哪一行都有两种跳法,比如第二行,B->H,H->J与J->P,P->R,找到每行第一种跳法的规律,第二种用2*numRows-2去减就可以了。
不难看出,第一种跳法的规律是2*numRows-2-2*i;第二种是2*i;那么怎样能让它按照两种跳法来跳呢?用奇数偶数循环就行,0,1,2…偶数,奇数,偶数…
代码:
class Solution {
public:
string convert(string s, int numRows) {
if(numRows<=0)
return "";
if(numRows==1)
return s;
int start;
string newstring;
for(int i=0;i<numRows;i++)
{
start = i;
newstring+=s[i];
for(int j=0;start<s.length();j++)
{
if(i==0||i==numRows-1)
start+=2*numRows-2;
else
{
if(j%2==0)
start+=2*(numRows-i)-2;
else
start+=2*i;
}
if(start<s.length())
newstring+=s[start];
}
}
return newstring;
}
};