leetcode编程记录4 #6 ZigZag Conversion

来源:互联网 发布:ipad淘宝hd详情打不开 编辑:程序博客网 时间:2024/05/18 00:27

leetcode编程记录4 #6 ZigZag Conversion

标签(空格分隔): leetcode


这次的题目是有关于字符串的输入问题,题目如下:

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”.

题目理解与分析:
这道题目的意思是将所给的字符串表示成一种蜿蜒(zigzag)的形式,之后再次一行一行地将所有字符转换为一个字符串,而且这些给出来的字符串的蜿蜒的程度是由,nRows这个参数来决定的,所给的参数有多大就将相应的字符串表示成几行。这样分析完这道题后,我们发现这道题并不难做,重要的是细节的处理,应该要考虑字符串的长度与所给行数参数的具体关系。
c++代码如下:

class Solution {public:    string convert(string s, int numRows) {        string result;        if(numRows <= 1)        {            return s;        }        else if(numRows == 2)        {            for (int i = 0; i < s.size(); i = i + 2)            {                result.push_back(s[i]);            }            for (int i = 1; i < s.size(); i = i + 2)            {                result.push_back(s[i]);            }        }        else        {            char temp[numRows][s.size()];            for(int i = 0; i < numRows; i++)            {                for (int j = 0; j < s.size(); j++)                {                    temp[i][j] = '\0';                }            }            int flag = 1;            for (int i = 0, j = 0, k = 0; i < s.size(); i++)            {                temp[j][k] = s[i];                if(j == numRows - 1 || j == 0)                {                    flag = ~flag;                }                if(flag != 1)                {                    j++;                }                else                {                    j--;                    k++;                }            }            for(int i = 0; i < numRows; i ++)            {                for (int j = 0; j < s.size(); j++)                {                    if(temp[i][j] != '\0')                    {                        result.push_back(temp[i][j]);                    }                }            }        }        return result;    }};
原创粉丝点击