标签:
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 RAnd 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"
.#include <stdio.h> #include <string> #include <stdlib.h> using namespace std; class Solution { private: string convStr; public: string convert(string s, int nRows) { int i=0, j=0,k=0; int length = s.length(); if (nRows == 1){ return s; } convStr = s; //first row for (i = 0; i < length; i += 2 * (nRows - 1), k++){ convStr[k] = s[i]; } //middle Rows for (i = 1; i < nRows - 1; i++, k++){ convStr[k] = s[i]; j = i; while (j < length){ if (j + 2 * (nRows - i - 1) < length){ k++; convStr[k] = s[j + 2 * (nRows - i - 1)]; } else{ break; } if (j+2*(nRows-1)<length){ k++; convStr[k] = s[j + 2 * (nRows- 1)]; } else{ break; } j += 2 * (nRows - 1); } } //last row; for (i = nRows - 1; i < length; i += 2 * (nRows - 1), k++){ convStr[k] = s[i]; } return convStr; } }; int main(){ Solution solution; printf("%s\n", solution.convert("PAYPALISHIRING", 3).c_str()); system("pause"); return 0; }
标签:
原文地址:http://www.cnblogs.com/JeromeHuang/p/4439674.html