ZigZag Conversion

来源:互联网 发布:淘宝哪些图片不能盗用 编辑:程序博客网 时间:2024/06/05 17:58

题目描述

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)
图片
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”.

题目解答

解题思路

  • 通过一个数组来保存每一行的内容,一个指针step来控制上下的移动
  • 通过数学规律来解决, l两两对
    参考博客
    图片2
    可以发现规律,画红色的长度永远是 2n-2 (想法是你试想把所有这些行压缩成两列,两边手挤一下,第二列永远的第一行和最后一行少字)。

    利用这个规律,可以按行填字,第一行和最后一行,就是按照2n-2的顺序一点点加的。

    其他行除了上面那个填字规则,就是还要处理斜着那条线的字,可以发现那条线的字的位置永远是当前列j+(2n-2)-2i(i是行的index)。

代码实现
public class Solution {    public String convert(String s, int numRows) {        if(s == null || s.length() == 0 || numRows == 0)            return "";        if(numRows == 1)            return s;         //存储每一行的内容        StringBuilder[] rowContent = new StringBuilder[numRows];        for(int i = 0; i < numRows; i++)            rowContent[i] = new StringBuilder();        int pos = 0;        int step = 0;        for(int i = 0; i < s.length(); i++){            //step控制上下移动            if(pos == (numRows-1))                step = - 1;            if(pos == 0)                step = 1;            rowContent[pos].append(s.charAt(i));            pos += step;        }        StringBuilder ret = new StringBuilder();        for(int i = 0; i < numRows; i++)            ret.append(rowContent[i]);        return ret.toString();    }}

规律

/**     * 通过数学规律来解决     *可以发现规律,一个来回的长度永远是 2n-2     利用这个规律,可以按行填字,第一行和最后一行,就是按照2n-2的顺序一点点加的。     其他行除了上面那个填字规则,就是还要处理斜着那条线的字,     可以发现那条线的字的位置永远是当前列j+(2n-2)-2i(i是行的index)--两两配对     */    public String convert2(String s, int numRows){        if(s == null || s.length() == 0 || numRows == 0)            return "";        if(numRows == 1)            return s;        int strLen = s.length();        int size = 2*numRows - 2;        StringBuilder ret = new StringBuilder();        for(int i = 0; i < numRows; i++){            for(int j = i; j < strLen; j += size){                ret.append(s.charAt(j));                if(i != 0 && i != (numRows-1)){                    int temp = j + size - 2*i;                    if(temp < strLen)                        ret.append(s.charAt(temp));                }            }        }        return ret.toString();    }
0 0
原创粉丝点击