Created
September 29, 2012 10:50
-
-
Save hyfrey/3803683 to your computer and use it in GitHub Desktop.
leetcode ZigZag Conversion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| 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". | |
| */ | |
| class Solution { | |
| public: | |
| string convert(string s, int nRows) { | |
| if (nRows == 1) { | |
| return s; | |
| } | |
| string ss; | |
| ss.reserve(s.size()); | |
| for (int i = 0; i < nRows; i++) { | |
| for(int j = 0, k = i; k < s.size(); j++) { | |
| ss.push_back(s[k]); | |
| if (i == 0 || i == (nRows-1)) { | |
| k += 2 * (nRows - 1); | |
| } else { | |
| if (j % 2 == 0) { | |
| k += 2 * (nRows - i - 1); | |
| } else { | |
| k += 2 * i; | |
| } | |
| } | |
| } | |
| } | |
| return ss; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment