Leetcode: 6. ZigZag Conversion(JAVA)

来源:互联网 发布:小米手机怎么开数据 编辑:程序博客网 时间:2024/06/09 22:38

【问题描述】

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   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);

【思路】


第0行和最后一行中,前一个下标的值和后一个下标的值相差 2 * nRows - 2

每行后所接的数字序号为2 * (nRows - 1 - i)

【code】

public class Solution {    public String convert(String s, int numRows) {if (s == null || s.length() < 0 || numRows <= 0) {return "";}if (numRows == 1) {return s;}StringBuffer sb = new StringBuffer();int size = numRows * 2 - 2;for (int i = 0; i < numRows; i++) {for (int j = i; j < s.length(); j += size) {sb.append(s.charAt(j));if (i != 0 && i != numRows - 1) {int temp = j + size - 2 * i;if (temp < s.length()) {sb.append(s.charAt(temp));}}}}return sb.toString();            }}


0 0
原创粉丝点击