zoukankan      html  css  js  c++  java
  • [LeetCode]ZigZag Conversion

    题目:ZigZag Conversion

    一串字符按照Z字形的数组给了我们,要求转成原本的顺序。

    思路:

    统计“|/”的个数;

    竖着的和斜着的下标有对应关系;

    竖着的:k = j*(2*numRows - 2) + i;

    斜着的(不含两个端点):k = (j + 1)*(2*numRows - 2) - i;

    注意:可能会有残缺的部分。

    /******************************************************************
    ZigZag Conversion
    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".
    ******************************************************************/
    #include <stdio.h>
    #include <memory.h>
    
    char* convert(char* s, int numRows) {
        int length = strlen(s);
        printf("%d
    ",length);
        if(length <= numRows || numRows <= 1)return s;
        int zn = length/(2*numRows - 2);//Z字形竖着放时,最开始的一竖和一撇的组合整体的个数
        int sn = length%(2*numRows - 2);//Z字形竖着放时,剩下残缺的组合的字母个数
        char *cs = (char *)malloc((length + 1)*sizeof(char));
        memset(cs,0,(length + 1)*sizeof(char));
        int index = 0,k = 0;
        for (int i = 0;i < numRows;i++){//完整组合的对应转换
            for(int j = 0;j < zn;j++){//竖线上的点坐标对应公式
                k = j*(2*numRows - 2) + i;
                cs[index++] = s[k];
                if(i > 0 && i < numRows - 1){//斜线上的不含两端点的点坐标对应公式
                    k = (j + 1)*(2*numRows - 2) - i;
                    cs[index++] = s[k];
                }
            }
            if(sn > i){//残缺组合的对应转换
                k = zn*(2*numRows - 2) + i;
                cs[index++] = s[k];
                if(i > 0 && i < numRows - 1 && sn > 2*numRows - 2 - i){
                    k = (zn + 1)*(2*numRows - 2) - i;
                    cs[index++] = s[k];
                }
            }
        }
        return cs;
    }
    
    void main(){
        char s[] = "Apalindromeisaword,phrase,number,orothersequenceofunitsthatcanbereadthesamewayineitherdirection,withgeneralallowancesforadjustmentstopunctuationandworddividers.";
        char *cs = convert(s,2);
        printf("%s
    ",cs);
        free(cs);
    }
  • 相关阅读:
    评审管理小结
    安全性测试入门 (五):Insecure CAPTCHA 验证码绕过
    安全性测试入门 (四):Session Hijacking 用户会话劫持的攻击和防御
    安全性测试入门 (三):CSRF 跨站请求伪造攻击和防御
    测试管理:问题驱动的测试过程改进
    逻辑思维驱动 (测试) 工作管理
    测试管理:用量化的思想管理工作
    软件质量报告模板-产品质量度量
    一篇短文再谈“敏捷”
    Windows XP系列全下载(均为MSDN原版)
  • 原文地址:https://www.cnblogs.com/yeqluofwupheng/p/6679118.html
Copyright © 2011-2022 走看看