ZigZag Conversion
来源:互联网 发布:网络交易平台 编辑:程序博客网 时间:2024/06/08 03:32
这题就很简单了,4分钟搞定
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 NA P L S I I GY 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"
.我的实现代码
public static String convert(String s, int numRows) { int point = numRows - 1, j = 0;String s0 = "";int i = point;if(i == 0) return s;int margin0 = i << 1;int margin = 0;while(i > 0) {margin = i << 1;j = point - i;while(j < s.length()) {s0 += s.charAt(j); j += margin; if(i != point) {margin = margin0 - margin; }}i--;}j = point - i;margin = j << 1;while(j < s.length()) {s0 += s.charAt(j); j += margin;} return s0; }
阅读全文