leetcode: 6. ZigZag Conversion

来源:互联网 发布:大学生滚床单知乎 编辑:程序博客网 时间:2024/05/25 12:21

一、问题描述

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

二、思路

  • 大概题意,按“之”字型排列给定的字符串,然后按行读取字符串,如下所示:
    这里写图片描述
  • 寻找规律
    • 对于第一行和最后一行,元素之间的间隔为distance = 2 * (rowNums - 1)
    • 对于其他的行,第一个元素与第二个元素之间的间隔distance1 = (numRows - 1) * 2 - i * 2,第二个元素与第三个元素之间的间隔distance2 = (numRows - 1) * 2 - distance1,第三个元素与第四个元素之间的间隔为distance1,第四个元素与第五个元素之间的间隔为distance2,依次类推
  • 特殊情况:rowNums为1,之间返回字符串即可

三、代码(Java)

public class Solution {    public String convert(String s, int numRows) {        //特殊情况        if (numRows == 1){            return s;        }        StringBuffer sb = new StringBuffer();        for (int i =  0; i < numRows; i++){       // 以第一列为基准,即以每一行的第一个字符的序号为准,求出同行的其他元素            if (i == 0 || i == numRows - 1){      // 处理第一行与最后一行                int j = i;                int distance = (numRows - 1) * 2;                while (j < s.length()){                    sb.append(s.charAt(j));                    j += distance;                }            } else {                              // 处理中间行                int j = i;                int distance = (numRows - 1) * 2 - i * 2;                while (j < s.length()){                    sb.append(s.charAt(j));                    j += distance;                    distance = (numRows - 1) * 2 - distance;                }            }        }        return sb.toString();    }}
原创粉丝点击