leetcode 题6 Z字形转换

将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。

比如输入字符串为 "PAYPALISHIRING" 行数为 3 时,排列如下:

P   A   H   N
A P L S I I G
Y   I   R
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"PAHNAPLSIIGYIR"。

请你实现这个将字符串进行指定行数变换的函数:

string convert(string s, int numRows);

 

求字符串的长度  s.length() 

 

本题目的实际是 对字符数组进行重新排序并保存。

然后就是找规律 看是按什么规则保存 

通过观察Z字形的字符串 可以以 2*(numRows-1) 为一个周期 即groupNum

第0行 的字符     字符的索引值 j %groupNum  == 0

第1 行字符  字符的索引值 j%groupNum == 1

一直到 numRows - 1 行    字符的索引值 j%groupNum ==  umRows - 1

 

一  方法一 遍历

因此 按照上述规律 依次遍历字符数组 存到新的数组中。   缺点耗时较长

另外 需要考虑特殊情况 :(1)numRows <= 1  (2) numRows > 1 但是 len < numRows

最后代码如下:

class Solution {
public:
    string convert(string s, int numRows) {
        if (numRows <= 1)
        {
            return s;
        }
        else
        {
            int len = s.length();
            if (len <= numRows )
            {
               return s;
            }
            else
            {
                int wordIdx = 0;
                string a = s ;
                int groupNum = 2*(numRows -1);
 
                for(int i = 0; i < numRows; i++)
                {
                    for (int j = 0; (j < len) && (wordIdx < len); j ++)
                    {
                        if(((j%groupNum) == i) || (groupNum - (j%groupNum) == i))
                        {
                            a[wordIdx] = s[j];
                            wordIdx++;              
                        }
                    }                    
                }
                return a;
            }
        }

    }
};

二  方法二 :方法一 中 存在的问题是 每统计一行就要 遍历一次字符串s  从而导致时间上的开销   

 为了解决上述问题,通过建立一个字符串数组,然后将每一行的字母存储起来再拼接

 

借鉴别人的思路:巧妙的利用flag。来计算行索引,从而填充numRows个字符串。

最后再拼接。

 

#include <string.h>​
class Solution {
public:
    string convert(string s, int numRows) {
    if (numRows <= 1)
    {
        return s;
    }
    string sFinal;
    string  tempString[numRows];
    int len = s.length();
    int rowIdx = 0;
    int flag = -1;
    for(int sIdx = 0; sIdx < len; sIdx++ )
    {
        tempString[rowIdx].append(1,(s[sIdx]));
        if(rowIdx == 0 || rowIdx == (numRows -1))
        {
            flag = -flag;
        }
        rowIdx += flag;
    }
    for (int rowIdx1 = 0; rowIdx1 < numRows; rowIdx1++)
    {
        sFinal.append(tempString[rowIdx1]);
    }
    return sFinal;
  }

};

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值