A 10-year-old problem
Apparently back in 2015 (10 years ago!) I tried to solve this problem several times, unsuccessfully. I was young and inexperienced, probably. I gave it another try now. The idea is to not have any sort of matrix. Basically, just keep track of the rows and have a hash table storing the strings in each row. As you move the row index, and you append the characters to the end of the strings, everything falls into place quite well. There is one odd case, when the number of rows is one, which doesn't really work in my calculations, hence I handle it separately in the beginning. Problem solved, only took 10 years. Code is down below, cheers, ACC.
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 s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation: P I N A L S I G Y A H R P I
Example 3:
Input: s = "A", numRows = 1 Output: "A"
Constraints:
1 <= s.length <= 1000
s
consists of English letters (lower-case and upper-case),','
and'.'
.1 <= numRows <= 1000
public string Convert(string s, int numRows) { //Special case: numRows = 1 if (numRows == 1) return s; Hashtable rows = new Hashtable(); int rowIndex = 0; bool direction = true; //true: down, false: up for (int i = 0; i < s.Length; i++) { if (!rows.ContainsKey(rowIndex)) rows.Add(rowIndex, ""); string str = (string)rows[rowIndex]; str += s[i].ToString(); rows[rowIndex] = str; rowIndex = direction ? rowIndex + 1 : rowIndex - 1; if (rowIndex >= numRows) { rowIndex = numRows - 2; direction = false; } else if (rowIndex < 0) { rowIndex = 1; direction = true; } } string retVal = ""; for (int i = 0; i < numRows; i++) { if (rows.ContainsKey(i)) retVal += (string)rows[i]; } return retVal; }
Comments
Post a Comment