• 【leetcode】ZigZag Conversion


    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".
     
    ZigZag的意思:
     
    一: 2排的时候,1到n的排序
    1 3 5 7 9  。。。
    2 4 6 8 10 。。。
     
     
    二: 3排的时候,1到n的排序
    1   5   9  。。。
    2 4 6 8 10 。。。
    3   7   11 。。。
     
    三: 4排的时候,1到n的排序
    1    7       13 。。。 
    2  6 8    12 14 。。。
    3 5  9  11   15 。。。
    4    10      16 。。。
     
    对于第一行(0)和最后一行(nRows-1),水平方向两个元素的间隔为:2(nRows-1)
    对于第i行来说,水平方向的两个元素间隔为2(nRows-1-i),2(i)
     
     
     1 class Solution {
     2 public:
     3     string convert(string s, int nRows) {       
     4         if(nRows==1)
     5         {
     6             return s;
     7         }
     8         string result;
     9         int n=s.length();
    10         int step;
    11         bool flag;
    12         for(int i=0;i<nRows;i++)
    13         {
    14             int j=i;
    15             flag=false;
    16             while(j<n)
    17             {
    18                 result.push_back(s[j]);
    19                 if(i==0||i==nRows-1)
    20                 {
    21                     step=2*(nRows-1);
    22                 }
    23                 else
    24                 {
    25                     if(flag==false)
    26                     {
    27                         step=2*(nRows-1-i);
    28                         flag=true;
    29                     }
    30                     else
    31                     {
    32                         step=2*i;
    33                         flag=false;
    34                     }
    35                 }
    36                 j+=step;
    37             }
    38         }       
    39         return result;
    40     }
    41 };
     
     
     
  • 相关阅读:
    PE 合并节
    VirtualAddress与VirtualSize与SizeOfRawData与PointerToRawData的关系
    .net core publish 找不到视图
    c++ rc 文件内包含中文字符导致在unicod环境下编译乱码
    .net 5.0 ref文件夹的作用
    .net 5.0项目升级工具
    HttpWebRequest DNS缓存清理
    .net 5.0 发布命令总结
    关于dll not found 排查解决
    关于win7 无法识别sha256签名导致驱动无法安装的问题
  • 原文地址:https://www.cnblogs.com/reachteam/p/4251631.html
Copyright © 2020-2023  润新知