[leetcode]ZigZagConversion

新博文地址:[leetcode]ZigZag Conversion

http://oj.leetcode.com/problems/zigzag-conversion/

写道
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".

 

看到讨论组里面有人用递归实现,代码简单的令人发指,但是当我看到这道题的第一反应是建模。。 太渣了。。。

public class Solution {
    public String convert(String s, int nRows) {
		if(nRows == 1){
			return s;
		}
		int strLength = s.length();
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < nRows; i++) {
			if (i == 0 || i == nRows - 1) {
				for (int m = 0; i + m * 2 * (nRows - 1) < strLength; m++) {
					sb.append(s.charAt(i + m * 2 * (nRows - 1)));
				}
			} else {
				for (int m = 0; 2 * m * (nRows - 1) + i < strLength || 2 * (m + 1) * (nRows - 1) - i < strLength; m++) {
					sb.append(s.charAt(i + m * 2 * (nRows - 1)));
					if (2 * (m + 1) * (nRows - 1) - i < strLength) {
						sb.append(s.charAt(2 * (m + 1) * (nRows - 1) -  i));
					}
				}
			}
		}
		return sb.toString();
	}
}

 

你可能感兴趣的:(conversion)