LeetCode 6 - ZigZag Conversion

一、问题描述

Description:

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".

根据给出的行数,按 “之” 字形排列源字符串,然后一行一行地输出字符串。


二、解题报告

本题主要是理解题意,输入一个字符串和一个行数,按“之”字形排列该字符串的字符,如下图:



这是 3 行的之字形,如果是 4 行的话:



以此类推。

思路:根据上面分析的规律,我们只需定义一个字符串数组,大小为行数(即每一行对应一个字符串)。然后遍历输入字符串,将每个字符插入对应行的字符串即可。

class Solution {
public:
    string convert(string s, int numRows) {
        if(numRows == 1)
            return s;

        vector<string> v(numRows,"");  // 创建numRows个字符串
        int idx = 0;
        bool flag = true;
        for(int i=0; i<s.size(); ++i)
        {
            v[idx] += s[i];

            if(flag)
                ++idx;
            else
                --idx;

            if(idx == numRows-1)
                flag = false;
            if(idx == 0)
                flag = true;
        }

        // 输出
        string output = "";
        for(int i=0; i<numRows; ++i)
            output += v[i];
        return output;
    }
};





LeetCode答案源代码:https://github.com/SongLee24/LeetCode


posted @ 2015-05-12 21:48  神奕  阅读(116)  评论(0编辑  收藏  举报