个人记录-LeetCode 6.ZigZag Conversion

来源:互联网 发布:mac系统突然很卡 编辑:程序博客网 时间:2024/04/28 12:40

问题:
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);

convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.

其实就是将字符串按锯齿的形式进行整理后,按顺序读出来。
将人写这种字符串的方式,用代码表现一下即可。

代码示例:

public class Solution {    public String convert(String s, int numRows) {        if(s == null) {            return null;        }        if (numRows <= 1) {            return s;        }        int len = s.length();        //为了速度比较快,采取空间换时间的方法        //分配数组存储结果的位图        char[][] temp = new char[numRows][len];        for (int i = 0; i < numRows; ++i) {            for (int j = 0; j < len; ++j) {                temp[i][j] = '\0';            }        }        char[] sChar = s.toCharArray();        int rowIndex = 0;        int columnIndex = 0;        //zigFlag为true,表示在处理锯齿的斜线部分        boolean zigFlag = false;        for (int i = 0; i < len; ++i) {            temp[rowIndex][columnIndex] = sChar[i];            if (!zigFlag) {                //正常形式,竖着写,增加行号即可                if (rowIndex + 1 < numRows) {                    ++rowIndex;                } else {                    --rowIndex;                    ++columnIndex;                    zigFlag = true;                }                continue;            }            //处理锯齿部分,就是斜着写,坐标处理一下就行            if (rowIndex - 1 >= 0 && columnIndex + 1 < len) {                --rowIndex;                ++columnIndex;            } else {                zigFlag = false;                ++rowIndex;            }        }        StringBuilder sb = new StringBuilder("");        for (int i = 0; i < numRows; ++i) {            for (int j = 0; j < len; ++j) {                if (temp[i][j] != '\0') {                    sb.append(temp[i][j]);                }            }        }        return sb.toString();    }}
0 0