美文网首页
6Z字形变换

6Z字形变换

作者: 无名的殇 | 来源:发表于2018-05-17 14:53 被阅读0次

    题目


    思路
    1.文字转换有固定规则
    2.在长度内有序取数
    代码

    char* convert(char* s, int numRows) {
        
        int len = 0, gap = 0, i = 0, j = 0, index = 0, next_j = 0;
        char *ret_s = NULL;
        
        if (NULL == s)
        {
            return NULL;
        }
        
        if (numRows < 2)
        {
            return s;
        }
        
        len = strlen(s);
        gap = numRows*2 - 2;//1个循环体间隔Z去掉最后一横的部分,也是每一排除掉中间部分的间隔位
        
        /*
         
         numRows = 3
         
         0   4   8
         1 3 5 7 9
         2   6
         
         */
        
        ret_s = malloc(len + 1);
        memset(ret_s, 0, len);
        
        for (i = 0; i < numRows; i++)
        {
            for (j = i; j < len; j += gap)
            {
                ret_s[index] = s[j];//间隔添加数据04815926
                index++;
                next_j = j + gap - i * 2;
                
                if (i != 0 && i != (numRows - 1) && next_j < len)//去掉第1排与最后排(无特殊数据)
                {
                    ret_s[index] = s[next_j];//添加特殊数据37
                    index++;
                }
            }
        }
        
        ret_s[len] = '\0';
        
        return ret_s;
    }
    

    相关文章

      网友评论

          本文标题:6Z字形变换

          本文链接:https://www.haomeiwen.com/subject/nrpbdftx.html