[LeetCode]ZigZag Conversion

题目来源:

https://leetcode.com/problems/zigzag-conversion/description/

很好理解的一个题目,就是输入一个字符串,然后按照之字形排列,然后将排列好的字符串从上到下输出,根据提供的两个例子很好看出题目的要实现的功能。

Example 1:

Input: s = “PAYPALISHIRING”, numRows = 3
Output: “PAHNAPLSIIGYIR”
Explanation:
P A H N
A P L S I I G
Y I R

Example 2:

Input: s = “PAYPALISHIRING”, numRows = 4
Output: “PINALSIGYAHRPI”
Explanation:

P I N
A L S I G
Y A H R
P I

实现上可以通过动态创建输入行数的字符串,然后依次填入对应的字符,最终将这几个子串拼接输出即可,实现如下:

class Solution {
public:
    string convert(string s, int numRows)
    {
        string *temp = NULL;
        string result;
        int index = 0;

        temp = new string[numRows];
        while(index < s.size())
        {
            for (int i = 0; i < numRows && index < s.size(); i++)
            {
                temp[i] += s[index];
                index ++;
            }

            for (int j = (numRows - 2); j >= 1 && index < s.size(); j --){
                temp[j] += s[index];
                index ++;
            }
        }

        for (int k = 0; k < numRows; k++)
        {
            result.append(temp[k]);
        }

        delete []temp;

        return result;
    }
};

这种实现方式提交后在LeetCode的提交时间上,处在39%的位置,不是最优的方法,还可以进行优化。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值