每日算法——letcode系列
問題 ZigZag Conversion
Difficulty: Easy
The string <code>"PAYPALISHIRING"</code> 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)
<pre>
P A H N
A P L S I I G
Y I R
</pre>
And then read line by line: <code>"PAHNAPLSIIGYIR"</code>
Write the code that will take a string and make this conversion given a number of rows:
<pre>string convert(string text, int nRows);</pre>
<code>convert("PAYPALISHIRING", 3)</code> should return <code>"PAHNAPLSIIGYIR"</code>.
class Solution {
public:
string convert(string s, int numRows) {
}
};
翻譯
Z(ZigZag)轉(zhuǎn)換
難度系數(shù):簡(jiǎn)單
字符串"PAYPALISHIRING"被以給定行的曲折形式寫成了下面的樣子:(有時(shí)候?yàn)榱朔奖汩喿x你可能需要以固定的字體寫成這種樣子) 注:從上往下再?gòu)南峦献x再
<pre>
P A H N
A P L S I I G
Y I R
</pre>
如果一行一行的讀應(yīng)該是 <code>"PAHNAPLSIIGYIR"</code>
要求:接收一個(gè)字符串,以給定的行數(shù)轉(zhuǎn)換成Z形字符串:
<pre>string convert(string text, int nRows);</pre>
<code>convert("PAYPALISHIRING", 3)</code> 應(yīng)返回 <code>"PAHNAPLSIIGYIR"</code>。
思路
此題理解題意重要寸五。 每一行對(duì)應(yīng)一個(gè)字符串拳缠,遍歷原字符串,然后把相應(yīng)的字符加到對(duì)應(yīng)行的字符串荣挨。
class Solution {
public:
string convert(string s, int numRows) {
int size = static_cast<int>(s.size());
// 當(dāng)行數(shù)小于等于1 或 大于原串的size時(shí)不用轉(zhuǎn)換
if (numRows <= 1 || numRows >= size) {
return s;
}
// 字符串?dāng)?shù)組, 裝的是行的對(duì)應(yīng)的字符串
vector <string> rowString(numRows);
int rowNum = 1;
// 向下讀還是向上讀的標(biāo)志
int flag = 1;
for (int i = 0; i < size; ++i) {
rowString[rowNum-1] += s[i];
if (rowNum == numRows){
flag = -1;
}
if (rowNum == 1) {
flag = 1;
}
rowNum += flag;
}
string result;
for (int i = 0; i < numRows; ++i) {
result += rowString[i];
}
return result;
}
};