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     }
  • 相关阅读:
    逆光拍摄常见的问题(解决大光比问题)
    HDP和包围曝光
    直方图
    linux查找文件的命令【转】
    100篇大数据文章[转]
    squid
    修改/etc/resolv.conf又恢复到原来的状态?[转]
    python字符串及正则表达式[转]
    GraphLab介绍[转]
    Scala 中的 apply 和 update 方法[转]
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3418461.html
Copyright © 2011-2022 走看看