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 }
  • 相关阅读:
    Vue 环境配置
    导入解决方案错误及其解决办法
    Dynamics 365创建用户提示:您正在尝试使用已由其他用户使用的域登录来创建用户。的解决办法
    iOS核心动画详解(CABasicAnimation)
    iOS核心动画详解(一)
    iOS 微信支付流程详解
    初探runtime
    iOS之block,一点小心得
    iOS scrollview循环播放加缩放
    用程序删除工程中多余的图片
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4255587.html
Copyright © 2011-2022 走看看