• leetcode------ZigZag Conversion


    标题: ZigZag Conversion
    通过率: 22.7%
    难度: 简单

    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("PAYPA


    LISHIRING", 3)
     should return "PAHNAPLSIIGYIR".

    看这个题看看还是没有明白。我去网上查时才看出来,下面我来解释一下:

    1、n=1时,

    0 1 2 3 4

    2、n=2时

    0 2 4 6 8
    1 3 5 7 9

    3、n=3时

    0   4   8
    1 3 5 7 9
    2   6   10

    3、n=4时

    0     6
    1   5 7
    2 4   8
    3     9

    看到这里就知道是什么样子的字符串了。输出时要按照一行一行的输出,在做的时候我只看出来第一行和最后一行的规律就是2*(nRows-1)相间隔.

    当n=1时直接返回,

    但是思考下面的时候我就不知道该怎么弄了。然后参考网上的解答我才看出来,1<n<nRows的时候两个两个元素是以 2*n和2*(nRows-1-n)相间隔的

    每一行的第一个一定是n,接着相隔2*(nRows-1-n)然后是2*n然后就是递归了。代码如下:

     1 public class Solution {
     2     public String convert(String s, int nRows) {
     3         String result="";
     4         boolean flag=true;
     5         if(nRows==1)return s;
     6         for(int i=0;i<nRows;i++){
     7             int j=i;
     8             flag=true;
     9             while(j<s.length()){
    10                 result+=String.valueOf(s.charAt(j));
    11                 if(i==0||i==nRows-1){
    12                     j+=2*(nRows-1);
    13                 }
    14                 else{
    15                     if(flag){
    16                         j+=2*(nRows-1-i);
    17                         flag=false;
    18                     }
    19                     else{
    20                         j+=2*i;
    21                         flag=true;
    22                     }
    23                 }
    24             }
    25         }
    26         return result;
    27         
    28     }
    29 }
  • 相关阅读:
    HI3518+RTSP(转)
    Linux常用命令英文全称与中文解释(转)
    旋转编码器正反转检测
    shell文件操作大全(转)
    makefile文件操作大全(转)
    Linux文件操作高频使用命令(转)
    浅谈linux中的根文件系统(转)
    分压电阻采样问题(转)
    python实现邮件发送
    50个很棒的Python模块
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4255587.html
Copyright © 2020-2023  润新知