码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode [006] : ZigZag Conversion

时间:2015-09-13 11:50:43      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

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、numRows可以计算出每多少个字母一个循环(例如,上面例子中为4个字母一个循环)

技术分享

2、竖直的字符个数为numRows,斜杠部分的字符个数实际上是numRows - 2,每(numRows * 2 - 2)个数字一个循环

3、每次偏移量增加(numRows * 2 - 2),依次输出即可。判断该位置是否有字符的唯一标准为是否越界,so easy

 

源代码如下:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

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

        string strResult;
        int iLen = s.size();
        int iCellNum = numRows * 2 - 2;

        for (int i = 0; i < numRows; ++i)
        {
            if (i == 0 || i == numRows - 1)
            {
                int j = i;
                while (j < iLen)
                {
                    strResult += s[j];
                    j += iCellNum;
                }
            }
            else
            {
                int j = i;
                int k = iCellNum - i;
                while (j < iLen)
                {
                    strResult += s[j];
                    j += iCellNum;
                    if (k < iLen)
                    {
                        strResult += s[k];
                        k += iCellNum;
                    }
                }
            }
        }

        return strResult;
    }
};

int main()
{
    Solution a;
    string strResult = a.convert("PAYPALISHIRING", 3);
    printf("%s\n", strResult.c_str());
    system("pause");
    return 0;
}

 

leetcode [006] : ZigZag Conversion

标签:

原文地址:http://www.cnblogs.com/lqy1990cb/p/4804174.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!