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".
Idea: Brute force. Use an array of stringbuilders to record the characters to be appended to each row. Then accumulate the substrings row by row. Please take care the initialization stringbuilder array is kind of special.
Time: O(n) Space: O(n) (can be easily reduced to O(1) if we append all the substrings to the first stringbuilder[0], but I used another variable for easier understanding).
Code:
public class Solution {
public String convert(String s, int nRows) {
StringBuilder[] builder=new StringBuilder[nRows];
for(int i=0;i<nRows;i++)
builder[i]=new StringBuilder();
int index=0;
while(index<s.length())
{
for(int i=0;i<nRows&&index<s.length();i++)
{
builder[i].append(s.charAt(index));
index++;
}
for(int i=nRows-2;i>0&&index<s.length();i--)
{
builder[i].append(s.charAt(index));
index++;
}
}
StringBuilder result=new StringBuilder();
for(int i=0;i<nRows;i++)
result=result.append(builder[i]);
return result.toString();
}
}
No comments:
Post a Comment