首页 > 其他 > 详细

LeetCode-6-ZigZag Conversion

时间:2019-01-27 16:16:04      阅读:153      评论: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 s, int numRows);

Example 1:

Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"

Example 2:

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:

P     I    N
A   L S  I G
Y A   H R
P     I

解题思路:

对于这个题目,网上查了很久,终于找到一个比较好的解题思路。

以Example2为例,从P到I的距离为 2*numRows -2 = 6。也就是说每六个元素为一个循环,因此可以为6取模作为元素所在行的索引。其中,对于索引值小于numRows的直接用索引值作为行号,而大于等于的值则采用补数作为索引值。

    string convert(string s, int numRows) {
        if(numRows <=1) return s;
        string results;
        vector<string> str(numRows,"");
        for(int i =0; i < s.size(); i++){
            int index = i % (2*numRows -2);
            index = index < numRows? index : 2*numRows -2 - index;
            str[index] += s[i];
        }
        for(int i=0; i < numRows; i++) results += str[i];
        return results;
    }

 

 

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 s, int numRows);

Example 1:

Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"

Example 2:

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:

P     I    N
A   L S  I G
Y A   H R
P     I

LeetCode-6-ZigZag Conversion

原文:https://www.cnblogs.com/nobodywang/p/10313285.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!