zoukankan      html  css  js  c++  java
  • leetcode: ZigZag Conversion

    http://oj.leetcode.com/problems/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".

    思路

    也许有更好的做法,但是最简单的方法就是先一层层的输出,最后重新拼成一个字符串。

     1 class Solution {
     2 public:
     3     string convert(string s, int nRows) {
     4         if (1 == nRows) {
     5             return s;
     6         }
     7 
     8         string result;
     9         vector<string> rows(nRows);
    10         int row = 0, i = 0;
    11         bool down = true;
    12         
    13         while (i < s.length()) {
    14             rows[row].push_back(s[i]);
    15             ++i;
    16             
    17             if (0 == row) {
    18                 down = true;
    19             }
    20             else if ((nRows - 1) == row) {
    21                 down = false;
    22             }
    23 
    24             if (down) {
    25                 ++row;
    26             }
    27             else {
    28                 --row;
    29             }
    30         }
    31         
    32         for (row = 0; row < nRows; ++row) {
    33             result += rows[row];
    34         }
    35         
    36         return result;
    37     }
    38 };
  • 相关阅读:
    Nginx中工作进程(work-process)为多少合适?
    Ubuntu中安装启动Nginx
    怎么获得类加载器?
    XML解析方式有哪些?
    HashMap常见面试题
    IO流分类
    集合之间的区别
    css布局2
    css布局1
    css3 总结01
  • 原文地址:https://www.cnblogs.com/panda_lin/p/zigzag_conversion.html
Copyright © 2011-2022 走看看