6. ZigZag Conversion

1、ZigZag Conversion——这是leedcode的第六题:
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”.

就是利用输入字符打印一个倒立之字形的图样。
具体样子可以看图:
6. ZigZag Conversion_第1张图片
6. ZigZag Conversion_第2张图片
解题思路
这里就是要计算各个字符的位置,推导出公式如下:
1、之字形行数为numRows,那么每次重复样出现前的间隔字符为repeatDis= numRows*2-2;
2、首行和末行存放一个字符的,并且存储的字符间隔为repeatDis;
3、中间行是需要额外存储多一个字符的,存储的字符位置是: repeatDis+ j - 2*i(其中i为行数,j为该行第几个字符)
这里需要考虑的主要是边界情况:
A、字符串长度小于等于行数;
B、行数小于等于1;
C、字符串长度小于3;
这里贴出Accept的代码:
Java版本:

public class Solution {
    public String convert(String s, int numRows) {
        if (s.length() <= numRows || s.length() < 3 || numRows <= 1) {
            return s;
        }
        String returnString = "";
        int repeatDis = 2 * numRows - 2;
        for (int i = 0; i < numRows; i++) {
            for (int j = i; j < s.length(); j += repeatDis) {
                returnString += s.charAt(j);
                if (i != 0 && i != numRows-1 && repeatDis + j - 2 * i < s.length()) {
                    returnString += s.charAt(repeatDis + j - 2 * i);
                }
            }
        }
        return returnString;
    }
}

C++版本:

class Solution {
public:
    string convert(string s, int numRows) {
        if (s.length() < 3 || s.length() < numRows || numRows <= 1) {
 return s;
        }
        string result;
        int repeateDis = numRows * 2 - 2;
        for (int i = 0; i < numRows; i++)
        {
            for (int j = i; j < s.length(); j += repeateDis) {
                result.push_back(s[j]);
                if (i != 0 && i != numRows - 1 && j + repeateDis - 2*i < s.length()) {
                    result.push_back(s[j + repeateDis - 2 * i]);
                }
            }
        }
 return result;
    }
};

你可能感兴趣的:(6. ZigZag Conversion)