• LeetCode6 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".   (Easy)

    分析:

    首先是理解题意,题目例子举得不好...起始ZigZag的意思以4举例更易懂一些。

    1           7             13

    2      6   8        12

    3   5      9   11

    4          10

    读懂了题意,其实就是判断好什么时候向下,什么时候向上即可,我用的vector<string>实现,维护nRows个string,最后拼接在一起。

    代码:

     1 class Solution {
     2 public:
     3     string convert(string s, int numRows) {
     4         if (numRows == 1) {
     5             return s;
     6         }
     7         vector<string> v(numRows);
     8         int j = 0;
     9         for (int i = 0; i < s.size(); ++i) {
    10             if ( (i / (numRows - 1) ) % 2 == 0) {
    11                 v[j].insert(v[j].end(), s[i]);
    12                 j ++;
    13             } 
    14             if ( (i / (numRows - 1)) % 2 == 1) {
    15                 v[j].insert(v[j].end(), s[i]);
    16                 j--;
    17             }
    18        }
    19        string result;
    20        for (int i = 0; i < v.size(); ++i) {
    21            result += v[i];
    22        }
    23        return result;
    24     }
    25 };
  • 相关阅读:
    谨以此文纪念一周的心血历程
    面向对象初调用:foolish 电梯
    洛谷 1016 旅行家的预算
    洛谷 1514 引水入城
    洛谷 3178 树上操作
    洛谷 3811 【模板】乘法逆元
    洛谷 1156 垃圾陷阱
    洛谷 1363 幻想迷宫
    洛谷 1736 创意吃鱼法
    洛谷 1436 棋盘分割
  • 原文地址:https://www.cnblogs.com/wangxiaobao/p/5730844.html
Copyright © 2020-2023  润新知