"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"
.
---
Solution: Iterate through the string, while maintaining the current row number that goes down and up and down and so on. Add each character to their current row number. Return the result by appending all characters in all rows together.
public class Solution {
public String convert(String s, int numRows) {
if (numRows == 1) return s;
List<List<Character>> rows = new ArrayList<>();
for (int i = 0; i < numRows; i++) {
rows.add(new ArrayList<>());
}
for (int i = 0, row = 0, dir = 1; i < s.length(); i++) {
rows.get(row).add((char) s.charAt(i));
row += dir;
if (row >= numRows) {
row = numRows - 2;
dir = -1;
} else if (row < 0) {
row = 1;
dir = 1;
}
}
StringBuilder sb = new StringBuilder(s.length());
for (List<Character> row: rows) {
for (Character c: row) {
sb.append(c);
}
}
return sb.toString();
}
}
No comments:
Post a Comment