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

ZigZag Conversion

时间:2016-01-02 22:34:30      阅读:218      评论: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"

Subscribe to see which companies asked this question

这种找规律的问题应该比较适合使用归纳法进行处理,不过光用肉眼看也能看出点规律。

设i 为行号,从1开始。numRows为行数

则1到7 是(1 + 2 * numRows - 2)

2到8 是(2 + 2 * numRows - 2)

2到6是(2 + 2 * numRows - 2) - 2

3到9是(3+ 2 * numRows - 2)

3到5是(3+ 2 * numRows - 2) - 2 * 2

注意行数为1的时候应该是返回本身

class Solution {
public:
    /*
     * 找规律
     * 1    7
     * 2  6 8
     * 3 5  9
     * 4    10
     *
     */
    string convert(string s, int numRows) {
            int len_s = s.length();
            if (1 == numRows) {
                return s;
            }
            string res = "";
          
            int i;
            for (i=0; i<numRows; i++) {
                int index = i;
                while (index < s.length()) {
                    res += s[index];
                    if (1 <= i && i<(numRows-1)) {
                        if ((index + 2 * numRows - 2 - 2 * i) < s.length()) {
                            //cout << (index + 2 * numRows - 2 - 2 * i) << endl;
                            res += s[index + 2 * numRows - 2 - 2 * i];
                        } else {
                            break;
                        }
                    }
                    index = (index + 2 * numRows - 2);
                }
            }
        return res;
    }
};

 

 

ZigZag Conversion

标签:

原文地址:http://www.cnblogs.com/SpeakSoftlyLove/p/5095257.html

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