6. Z字形变换

一、题目

将字符串 "PAYPALISHIRING" 以Z字形排列成给定的行数:

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

之后从左往右,逐行读取字符:"PAHNAPLSIIGYIR"

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

string convert(string s, int numRows);

示例 1:

输入: s = "PAYPALISHIRING", numRows = 3
输出: "PAHNAPLSIIGYIR"

示例 2:

输入: s = "PAYPALISHIRING", numRows = 4
输出: "PINALSIGYAHRPI"
解释:

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

二、思路

要得到解释后的二维数conStr[numRows][len]; len未知的情况下,找规律

 len = s.length()/ (2*numRows - 2) * (numRows - 1); 

解释一下将一个有完整列的如:PAYP这一列到ISHI这一列,有 numRows - 2个字符,加上完整的一列则为 2*numRows -2个字符 而这种规律递进的行长为 numRows - 1, 当然 len != s.length() / 2; 计算机运算取整!! 

当然还有不规律的,如最后的NG这一列,其判读 otherstr = s.length()% (2*numRows - 2) 

判断他的列数进行相加得到最后的len 那么接下来就填充再取出就好了 

三、代码

public class LeetCode6 {
    public static void main(String[] args){
        String s = "PAYPALISHIRING";
        System.out.println(convert(s,9));
    }
    public static String convert(String s, int numRows) {
        if(numRows == 1 )
            return s;
        int len = s.length() / (2*numRows - 2) * (numRows - 1);
        int otherStr = s.length() % (2*numRows - 2),otherLen = 0;
        if(otherStr != 0 ){
            if(otherStr <= numRows)
                otherLen = 1;
            else
                otherLen = otherStr - numRows + 1;
        }
        len = len + otherLen;
        char conStr[][] = new char [numRows][len];
        int k = 0 , l ,i = 0,j = 0;
        while(k < s.length()){
            //填充完整的一列
            i = 0; l = numRows;
            while(l > 0 && k < s.length()){
                conStr[i][j] = s.charAt(k);
                i++; k++; l--;
            }
            //像右推进一列,行数回归到非完整的起始行
            j++; i = numRows - 2;
            //填充非完整的列
            for(int z = numRows - 2;z > 0;z--){
                if(k < s.length()){
                    conStr[i][j] = s.charAt(k);
                    i--; j++; k++;
                }
            }
        }
        StringBuilder changedStr = new StringBuilder() ;
        for( i = 0 ; i < numRows ; i++){
            for( j = 0 ; j < len ; j++){
                if(conStr[i][j] != '\0'){
                    changedStr.append(conStr[i][j]);
                }
            }
        }
        return new String(changedStr);
    }
}

四、总结

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值