6. ZigZag Conversion

16 篇文章 0 订阅
2 篇文章 0 订阅

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".

我的思路:

对于 numsRows > 2 的情况,找出原字符串和新字符串每个字符下标的对应关系。

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

如上图所示,对于原字符串中的每个元素,其在新字符串中的下标即为在他之前的元素数目 num,num 由两部分组成,一部分是该元素所在行之上所有行的元素数目,另一部分是该元素所在行中在该元素左边的元素数目。

具体实现如下:

char* convert(char* s, int numRows) {
    int n = 0;
    while(s[n] != '\0') n++;
    if(numRows == 1 || n <= numRows) return s;
    char* sn = (char*)malloc((n + 1) * sizeof(char));
    sn[n] = '\0';
    if(numRows == 2){
        int rowLen = n / 2;
        if(n % 2) rowLen += 1;
        for(int i = 0;i < n;i++) sn[(i % 2) * rowLen + i / 2] = s[i];
        return sn;
    }
    int* rowLens = (int*)malloc((numRows + 1) * sizeof(int));
    rowLens[0] = 0;
    int Len = n / (2*numRows - 2),tail = n % (2*numRows - 2);
    rowLens[1] = Len,rowLens[numRows] = Len;
    for(int i = 2;i < numRows;i++) rowLens[i] = 2*Len;

    if(tail > 0){
        for(int i = 1;i < tail + 1 && i <= numRows;i++) rowLens[i]++;
        if(tail > numRows){
            tail -= numRows;
            for(int i = numRows - 1;tail > 0;i--){
                rowLens[i]++;
                tail--;
            }
        }
    }
    for(int i = 1;i <= numRows;i++) rowLens[i] += rowLens[i-1];
    for(int i = 0;i < n;i++){
        int unitIndex = i / (2*numRows - 2),InnerIndex = i % (2*numRows - 2);
        if(0 < InnerIndex && InnerIndex + 1 < numRows) sn[rowLens[InnerIndex] + 2*unitIndex] = s[i];
        else if(InnerIndex + 1 > numRows) sn[rowLens[numRows - (InnerIndex + 1 - numRows) - 1] + 2*unitIndex + 1] = s[i];
        else sn[rowLens[InnerIndex] + unitIndex] = s[i];
    }
    return sn;
}
看了其他人的解法,发现自己写的太麻烦了。。其实直接用一个字符串数组去存储每一行的字符,最后一批一拼接就行了。还可以找规律,具体的在 这里
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值