leetcode每日一题:(6)ZigZag Conversion

ZigZag Conversion

Question

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

题解

可以发现首行和末行的重复周期都是 2 * nRows - 2,对于首行和末行之间的行,还会额外重复一次,重复的这一次距离本周期起始字符的距离是 2 * nRows - 2 - 2 * i 。

C++

class Solution {
public:
    string convert(string s, int nRows) {
        if (nRows <= 1 || s.length() == 0)  //nRows=1 按下面会死循环
           return s;  
        string ret = "";
        const int len = s.size();
        int lag = 2*nRows - 2; //循环周期  
        for (int i = 0; i < nRows; i++) {  
            for (int j = i; j < len; j += lag) {  
                ret += s[j];    
                if (i > 0 && i < nRows-1) {  //非首行和末行时
                    int t = j + lag - 2*i;  
                    if (t < len) {  
                        ret += s[t];  
                    }  
                }  
            }  
        }  
        return ret;
   
    }
};

提交成功

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

相关阅读更多精彩内容

  • LeetCode 刷题随手记 - 第一部分 前 256 题(非会员),仅算法题,的吐槽 https://leetc...
    蕾娜漢默阅读 18,230评论 2 36
  • LeetCode -- 6. ZigZag Conversion 题目描述 The string "PAYPALI...
    sea_baby阅读 3,294评论 0 0
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,357评论 0 33
  • 绘制思维导图就是将隐性思维显性化的过程,这个过程比普通的文本阅读和理解包含了更为丰富的提取过程,能够更清晰地帮助人...
    晓蕊阅读 1,373评论 0 0
  • 今日收获 1.晚上在马路上奔跑,骑车太爽了。 2.鹿鼎记好好看。 3.与朋友聚会比学习更重要。菁菁要走了。 小确幸...
    Yivan_1996阅读 1,225评论 0 0

友情链接更多精彩内容