入力された文字列"PAYPALISHIRING"は、指定された行数でジグザグに書かれ:
P A H N
A P L S I I G
Y I R
そして1行ずつで読まれる:"PAHNAPLSIIGYIR"。
こんな文字列を変換する関数string convert(string text, int nRows);を実現せよ。
例えば、convert("PAYPALISHIRING", 3)が "PAHNAPLSIIGYIR" .をリターンすべきです。
解:
紙の上で文字のインデックスとその位置を描いてみたら、簡単にその関係性を発見できるはずです。あとは出力文字列を構築するだけです。ひとつ注意すべき点は、nRowsが1であるときです。
C#のコードは以下です。
public class Solution
{
public string Convert(string s, int numRows)
{
if (numRows<2) return s;
StringBuilder sb = new StringBuilder();
int step = 2 * numRows - 2;
for (int i=0; i<s.Length; i+= step)
{
sb.Append(s[i]);
}
for (int line = 1; line < numRows-1; line++)
{
for (int i = 0; i<s.Length; i+= step)
{
if (i + line < s.Length) sb.Append(s[i+line]);
if (i + step - line < s.Length) sb.Append(s[i + step - line]);
}
}
for (int i = numRows - 1; i<s.Length; i+= step)
{
sb.Append(s[i]);
}
return sb.ToString();
}
}