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

    这个题很简单,分级也是easy级别的,但是一个小bug差点把我逼疯,天知道我在想什么。

    题意:把字符串Z字形排列,然后返回横向,也就是正常阅读方向的字符串。

    思路:

    首先观察Z字形排列的字符串的特点:

    0       8
    1     7 9
    2   6   10
    3 5     11
    4       12
    0   4  
    1 3 5 7
    2   6  

    从图上可以看出,在最边上的两行,每两个相邻字符的索引相差2*numRows-2,同时,在其余行,两个平行行之间的三个字符,

    相邻两个字符索引的差之和也为2*numRows-2。利用这个特点,解法就是:

     1 char* convert(char* s, int numRows) {
     2     int len=strlen(s);
     3     int gap,d,rd,i,j,k=0;
     4     char*tmp=malloc(sizeof(char)*(len+1));
     5     gap=2*numRows-2;
     6     d=gap;
     7     if(numRows!=1)
     8          for(i=0;i<numRows;i++)
     9         {
    10             rd=d;
    11             tmp[k++]=s[i];
    12             if(i==numRows-1)
    13                 rd=gap;
    14             for(j=i+rd;j<len;j=j+rd)
    15                 {
    16                     tmp[k++]=s[j];
    17                     if(i!=0&&i!=numRows-1)
    18                         rd=gap-rd;        //关键在这个,
    19                 }
    20             d-=2;
    21         }
    22     else
    23     {
    24         k=0;
    25         while(k<len)
    26             {
    27                 tmp[k]=s[k];
    28                 k++;
    29             }
    30     }
    31             tmp[k]='';
    32     return tmp;
    33 }
  • 相关阅读:
    Navicat在MySQL中添加外键详细过程
    java绘图原理------在窗口界面(或面板上)画出一张或多张图片问题解决方法
    记录springboot jar包冲突异常处理
    终止线程
    SpringDataJPA
    mysql安装后无法启动问题
    地理空间几种数据格式
    图幅与经纬度之间的换算
    postgresql12集成postgis与timescale
    C# 微信支付 V2
  • 原文地址:https://www.cnblogs.com/fcyworld/p/6194685.html
Copyright © 2011-2022 走看看