LeetCode 6 ZigZag Conversion题解

来源:互联网 发布:ubuntu for arm 编辑:程序博客网 时间:2024/05/29 16:29

题目地址:https://leetcode.com/problems/zigzag-conversion/

题目:

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)

字符串"PAYPALISHIRING"写成给定行数的循环对角结构,如下:(你可能想要将这个图形修改的更加易读)

P   A   H   NA P L S I I GY   I   R

And then read line by line: "PAHNAPLSIIGYIR"

然后一行行读成“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".

转化“PAYPALISHIRING,3”应得“PAGNAPLSIIGYIR”


题解:

1)什么是ZigZag(循环对角结构)?

举个5行的ZigZag存储1到n的数字的例子,如下图:

1   9   17...2  810  1618...3 7 11 15 19...46  1214  20...5   13   21...


2)存储特点

给定行数为rowsNum,行号为0~rowsNum-1。

我们可以看出,整列的数字,同一行的两个数字之间相差2*(rowsNum-1),比如第一行的1,9,17,相差8=2*(行数为5-1)。

整列数字间的数字,与同行下一数字相差2*行号,比如第二行的8和10差2=2*行号为1,第三行的7和11差4=2*行号为2。(这样的数字位置特点:非首行,非末行),)

3)C++代码

class Solution {public:    string convert(string s, int numRows) {        int l=s.length();        string str="";        if(l==0)            return str;        if(numRows==1||l<=numRows)            return s;        else        {            for(int j=0;j<numRows;j++)            {                for(int i=j;i<l;i+=(numRows-1)*2)                {                    str+=s.at(i);                    if(j!=0&&j!=numRows-1&&i+(numRows-1)*2-2*j<l)                    {                        str+=s.at(i+(numRows-1)*2-2*j);                    }                                    }            }        }        return str;    }};

4)Java代码

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



0 0
原创粉丝点击