LeetCode 6. Z 字形变换 ZigZag Conversion(C语言)

题目描述

将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 “LEETCODEISHIRING” 行数为 3 时,排列如下:
《LeetCode 6. Z 字形变换 ZigZag Conversion(C语言)》
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“LCIRETOESIIGEDHN”。
请你实现这个将字符串进行指定行数变换的函数:

string convert(string s, int numRows);

示例 1:

输入: s = “LEETCODEISHIRING”, numRows = 3
输出: “LCIRETOESIIGEDHN”

示例 2:

输入: s = “LEETCODEISHIRING”, numRows = 4
输出: “LDREOEIIECIHNTSG”
解释:
《LeetCode 6. Z 字形变换 ZigZag Conversion(C语言)》

题目解答:

方法1:找规律

该题是一个找规律的题,需要确定哪些位置的字符会放在同一行。通过分析可以看出来,对于某一行 i ,假定当前字符A位置为temp,如果2n - 2i - 2不为0,则同一行的下一个字符B位置就是temp + 2n - 2i - 2,接下来如果2i不为0,则下一个字符C位置为temp + 2i(temp已更新为上一个字符B的位置),接下来继续重复上述过程,直到temp大于字符串长度。运行时间12ms,代码如下。

char* convert(char* s, int numRows) {
    int n = numRows, index = 0;
    int len = strlen(s), temp = 0;
    int i = 0, t = 2 * n - 2;
    char* result = (char*)malloc((len + 1) * sizeof(char));
    result[len] = '\0';
    if(n == 1) {
        memcpy(result, s, len * sizeof(char));
        return result;
    }
    for(i = 0; i < n; i++) {
        result[index++] = s[i];
        temp = i;
        while(1) {
            if(t - 2 * i) {
                if(temp + t - 2 * i < len) {
                    temp += (t - 2 * i);
                    result[index++] = s[temp];
                }
                else
                    break;
            }
            if(2 * i) {
                if(temp + 2 * i < len) {
                    temp += 2 * i;
                    result[index++] = s[temp];
                }
                else
                    break;
            }
        }
    }
    return result;
}
    原文作者:Z字形编排问题
    原文地址: https://blog.csdn.net/hang404/article/details/84839234
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞