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

題解

可以發(fā)現(xiàn)首行和末行的重復(fù)周期都是 2 * nRows - 2,對于首行和末行之間的行,還會額外重復(fù)一次,重復(fù)的這一次距離本周期起始字符的距離是 2 * nRows - 2 - 2 * i 。

C++

class Solution {
public:
    string convert(string s, int nRows) {
        if (nRows <= 1 || s.length() == 0)  //nRows=1 按下面會死循環(huán)
           return s;  
        string ret = "";
        const int len = s.size();
        int lag = 2*nRows - 2; //循環(huán)周期  
        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;
   
    }
};

提交成功

提交成功
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • LeetCode 刷題隨手記 - 第一部分 前 256 題(非會員),僅算法題,的吐槽 https://leetc...
    蕾娜漢默閱讀 18,392評論 2 36
  • LeetCode -- 6. ZigZag Conversion 題目描述 The string "PAYPALI...
    sea_baby閱讀 514評論 0 0
  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,923評論 0 33
  • 繪制思維導(dǎo)圖就是將隱性思維顯性化的過程,這個過程比普通的文本閱讀和理解包含了更為豐富的提取過程,能夠更清晰地幫助人...
    曉蕊閱讀 197評論 0 0
  • 今日收獲 1.晚上在馬路上奔跑,騎車太爽了。 2.鹿鼎記好好看。 3.與朋友聚會比學(xué)習(xí)更重要。菁菁要走了。 小確幸...
    Yivan_1996閱讀 155評論 0 0

友情鏈接更多精彩內(nèi)容