zoukankan      html  css  js  c++  java
  • 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".

    很麻烦的找规律的题。

    1.规律是锯齿状的,|/|/|/ ...

    2.找到规律后依然很难弄。最简单的方法是申请个二维数组,填进去,再读出来。仔细观察后发现每一行字母下表有规律,利用规律计算可以减少空间浪费。最后把任务分成首行、中间行、尾行三部分处理完。

    class Solution {
    public:
        string convert(string s, int nRows) {
            if(nRows == 0)return "";
            if(nRows == 1)return s;
            
            int num = s.length();
            int group = 2*nRows -2;
            int flag = 0;
            int n_group;
            if(num%group == 0) n_group =num/group;
            else n_group =num/group+1;
            
            string re = "";
            for(int i = 0 ; i < n_group ; i++)
            if(i*group<num)re += s[i*group];
            for(int i = 1 ; i < nRows -1;i++)
            {
                for(int j = 0 ;j <n_group ;j++)
                {
                    if(j *group + i < num) re += s[j *group + i];
                    if((j+1) *group - i < num) re += s[(j+1) *group - i ];
                }
            }
            for(int i = 0 ; i < n_group ; i++)
            if(group*i + nRows-1 <num)re+=s[group*i + nRows-1];
            return re;
        }
    };
  • 相关阅读:
    Linux下挂载新硬盘
    远程编写+调试服务器上的Python程序
    记一次CUDA编程任务
    CUDA核函数调用基础数学API的一个奇葩情况
    Python多线程常用包对比
    Python threadpool传递参数
    代码生成器
    从移动优先到离线优先(三)
    从移动优先到离线优先(二)
    从移动优先到离线优先(一)
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3583474.html
Copyright © 2011-2022 走看看