leetcode编程记录4 #6 ZigZag Conversion

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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值