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

思路

找规律,比较简单,在纸上画几个例子就行了。就是要注意处理几个特殊情况。

实现

class Solution {
public:
    string convert(string s, int numRows) {
        string ans;
        for(int j=0; j<numRows; j++){
            for(int i=j; i<s.size(); i+=2*numRows-2){
                ans.push_back(s[i]);
                int idx_next = i + 2 * (numRows - j - 1);
                if(j>0 && j<numRows-1 && idx_next<s.size()){
                    ans.push_back(s[i+2*(numRows)]);
                }
            }
        }
        return ans;
    }
};

思考

时间比较紧的时候,可以将首尾行分别用两个循环处理,将行数为1的情况单独处理。简单粗暴有时候更加有效,不用想着如何让代码高度压缩统一。
另外此题在计算中间行时,可以让循环的步长不断在两种情况下变化。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容