zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    selenium 操作过程中,元素标红高亮的两种实现方式
    python pytest测试框架介绍五---日志实时输出
    pytest 3.9在python 2.7下的一个bug
    Qt assis tant 帮助集合文档 -由.qhcp生成.qhc
    Qt assistant .qch显示乱码问题
    qhelpgenerator 由qhp生成qch过程碰到的问题 记录
    Qt creator新建widget项目....no valid kits found.....
    Qt creator 账号
    Qt 写Excel
    Qt获取主窗口
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4255587.html
Copyright © 2011-2022 走看看