LeetCode-6-之字形变换-C语言

本文介绍了一种将字符串以之字形方式排列并转换的算法实现。通过使用多个字符数组来存储每行的字符,按照之字形的路径填充字符,最后整合成新的字符串。该算法适用于多行显示的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


/*
* 算法思想:
* 使用numRows个字符数组,分别存储每行的字符;
* 按照之字形的方式分别将所给字符填进numRows个字符数组;
* 最后将numRows个字符数组中的字符取出来放到s数组中,返回s即可。
*
*
*/

int get_len(char *s){
    int i=0;
    
    while(*s != '\0'){
        s++;
        i++;
    }
    return i;
}


char * convert(char * s, int numRows){
    int len = get_len(s);
    
    /* 一行时,以及长度为0时候,不需要 */
    if(!len || numRows <= 1){
        return s;
    }

    char arr[numRows][len+1];
    int indexs[numRows];
    
    memset(arr, 0, sizeof(arr));
    memset(indexs, 0, sizeof(indexs));
    
    int i = 0;
    int derect = 0;
    int flag = 0;/* 用于表示是行数递增方向还是递减方向 */
    while(s[i] != '\0' ){
        if(flag == 0){
            /* 递增方向 */
            arr[derect][indexs[derect]++] = s[i++];    
            derect++;
            /* 递增到头的时候,将其回头 */
            if(derect >= numRows){
                flag = 1;
                derect -= 2;
            }
        }else {
            /* 递减方向 */
            arr[derect][indexs[derect]++] = s[i++];    
            derect--;
            /* 递减到头的时候,将其回头 */
            if(derect < 0){
                flag = 0;
                derect += 2;
            }  
        }
    }
    
    int index = 0;
    int j=0;
    /* 取每行的字符放到字符串s中 */
    for(i=0; i<numRows; i++){
        j=0;
        while(arr[i][j] != 0){
            s[index++] = arr[i][j++];
        }
    }
    
    return s;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值