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

    思路:

    最开始题意理解不清楚,后来看了下面这组图以后就明白了,找规律解决即可。

    nRows = 2
    0 2 4 6 8
    1 3 5 7 9
    nRows = 3
    0   4   8     12    16
    1 3 5 7 9  11 13 15
    2   6   10    14
    nRows = 4
    0     6       12       18
    1   5 7    11 13    17 19
    2 4   8 10    14 16
    3     9       15

    代码:

     1     string convert(string s, int nRows) {
     2         // IMPORTANT: Please reset any member data you declared, as
     3         // the same Solution instance will be reused for each test case.  
     4         if(nRows == 1)
     5             return s;  
     6         vector<string> tmp(nRows,"");
     7         int step = 0, cur = 0;
     8         int l = s.length();
     9         while(cur < l){
    10             if(step == 0){
    11                 int i;
    12                 for(i = 0; i < nRows && cur+i < l; i++)
    13                     tmp[i] += s[cur+i];
    14                 if(i < nRows)
    15                     break;
    16                 cur += nRows;
    17             }
    18             else{
    19                 tmp[nRows-1-step] += s[cur];
    20                 cur++;
    21             }
    22             step = (step+1)%(nRows-1);
    23         }
    24         string result = "";
    25         for(int i = 0; i < nRows; i++)
    26             result += tmp[i];
    27         return result;
    28     }
  • 相关阅读:
    java 上传图片
    getElementById 鼠标经过字体改变颜色
    getElementById 学习
    css的绝对定位与相对定位
    关于For循环
    扩展方法的应用
    关于Function 的学习笔记
    <a>标签中查找文件的方法
    关于Name ID class属性的区别
    使用float设置经典的网站前端结构
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3418461.html
Copyright © 2011-2022 走看看