【Leetcode】【ZigZag conversion】【Z字形变换】【C++】

本文介绍了如何将字符串以Z字形方式排列成指定行数的方法,并提供了两种实现思路及对应的C++代码示例。一种是通过构建字符数组再逐行读取,另一种则是根据Z字形规律直接计算。
  • 题目:将给定字符串以Z字形排列成给定的行数: 如"PAYPALISHIRING" ,numRows=3

P    A    H   N

A P L S  I  I G

Y    I      R    之后从左到右排列,逐行读取字符:得到"PAHNAPLSIIGYIR"并返回

 

  • 思路1:将Z字形字符数组存储到一个字符数组中,然后按行读取字符。
  • 思路2:直接根据规律计算。
  • 代码1:
class Solution {
public:
    string convert(string s, int numRows) {
        int len_s=s.size();
        if(numRows==1)
            return s;
        int numCols=(numRows-1)*len_s/(numRows*2-2)+numRows-1;
        
        
        char res[numRows][numCols];
        for(int i=0;i<numRows;i++)
        {
            for(int j=0;j<numCols;j++)
            {
                res[i][j]=' ';
            }
        }
            
        int cur_row=0;
        int cur_col=0;
        bool down=true;
        for(int i=0;i<len_s;i++)
        {
            if(down)
            {
                res[cur_row][cur_col]=s[i];
                if(cur_row && cur_row==(numRows-1))
                {
                    down=false;
                    cur_row--;
                    cur_col++;
                }
                else
                {
                    cur_row++;
                }
            }
            else
            {
                res[cur_row][cur_col]=s[i];
                if(cur_row==0)
                {
                    down=true;
                    cur_row++;
                }
                else
                {
                    cur_row--;
                    cur_col++;
                }
            }
        }
        numCols=cur_col+1;
        string str="";
        for(int i=0;i<numRows;i++)
        {
            for(int j=0;j<numCols;j++)
            {
                if(res[i][j]!=' ')
                    str+=(res[i][j]);
            }
        }
        return str;
    }
};
  • 代码2:
class Solution {
public:
    string convert(string s, int numRows) {
        if(numRows==1)
            return s;
        int n=numRows*2-2;
        int len_s=s.size();
        
        string res="";
        
        for(int i=0;i<numRows;i++)
        {
            int index=i;
            
            while(index<len_s)
            {
                res+=s[index];
                
                if(i!=0 && i!=(numRows-1) && index+n-2*(i%n)<len_s)
                {
                    res+=s[index+n-2*(i%n)];
                }
                
                index=index+n;
            }  
        }
        return res;
        
    }
};

 

转载于:https://www.cnblogs.com/dreamer123/p/9163063.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值