您的位置:首页 > 其它

LeetCode ZigZag Conversion

2015-10-14 22:27 387 查看
题目:

[code]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".


分析:

题目要求对一个字符串按给定的行数呈‘Z’形排列,

[code]0     6
1   5 7
2 4   8
3     9


仔细研究发现,每2*numRows - 2个字符是一组,即

[code]0     
1   5 
2 4   
3


是一组,其实本题考查的是对mod的运用,看出这一点就不难找出规律了

代码:

[code] public String convert(String s, int numRows) {
        StringBuilder res = new StringBuilder();
        int len = s.length();
        if(len == 0 || numRows == 1)
            return s;
        int group = 2 * numRows - 2;
        int col ;
        if(len % group <= numRows - 1)
            col = (len / group) * (numRows - 1) + 1;
        else
            col = (len / group) * (numRows - 1) + len % group + 1 - numRows;
        char [][] tmp = new char[numRows][col];
        for(int i = 0;i < numRows;i++)
            for(int j = 0;j<col;j++)
                tmp[i][j] = '/';
        for(int i = 0;i < len;i++)
        {
            int tmp_row,tmp_col;
            if(i % group <= numRows - 1)
            {
                tmp_row = i % group;
                tmp_col = (i / group) * (numRows - 1);
            }
            else
            {
                tmp_row = group - i % group;
                tmp_col = ((i % group) - numRows + 1) + (i / group) * (numRows - 1);
            }
            tmp[tmp_row][tmp_col] = s.charAt(i);
        }
        for(int i = 0 ;i < numRows;i++)
            for(int j = 0;j < col;j++)
                if(tmp[i][j] != '/')
                    res.append(tmp[i][j]);
        return res.toString();

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: