Not very difficult. It is a typical "pattern" style question. Once some test cases are verified, you can see that the number of chars in diagonal should be nRows - 2, so every (nRows + nRows - 2) chars should be one pattern. (nRows is number of chars in vertical direction).
public class Solution {
public String convert(String s, int nRows) {
if(s == null || s.equals("") || nRows <= 1) return s;
StringBuffer [] rows = new StringBuffer[nRows];
for(int i = 0;i < nRows; i++){
rows[i] = new StringBuffer();
}
int rowIdx = 0;
for(int i = 0; i < s.length(); i ++){
int tmp = i%(nRows + nRows - 2);
if(tmp < nRows){// simple cases, should in the vertical column
rows[tmp].append(s.charAt(i));
}
else{// a little complicated, in the diagonal
rows[(nRows - 1) - (tmp - (nRows - 1))].append(s.charAt(i));
}
}
StringBuffer res = new StringBuffer();
for(int i = 0 ; i < nRows; i++)res.append(rows[i]);
return res.toString();
}
}
Hello, welcome to Yizhe's Blog. I am Yizhe Liu, graduated from University of Arizona, with Master degree, major in Electrical and Computer Engineering. Actually, I am software guy. In my blog, many posts are about the Leetcode questions. I will post my ideas and implementations, which are accepted by Leetcode. If you have different opinions, please leave comment. I am happy to discuss with you. So lets start rocking them!!!
No comments:
Post a Comment