生活随笔
收集整理的這篇文章主要介紹了
算法:z字型变换
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?題目:
將字符串 “PAYPALISHIRING” 以Z字形排列成給定的行數:
P ? A ? H?? N
A P L S I ?I G
Y ? I ?? R
之后從左往右,逐行讀取字符:“PAHNAPLSIIGYIR”
實現一個將字符串進行指定行數變換的函數:ensp
string convert(string s, int numRows);
示例 1:
輸入: s = “PAYPALISHIRING”, numRows = 3
輸出: “PAHNAPLSIIGYIR”
//z字型變換:先按Z字型排列,然后橫著輸出
//numRows為對應斜著的個數//按行排序
//numRows表示行數,就是豎著的單詞
class Solution {
public:string convert(string s, int numRows) {if (numRows == 1) return s;vector<string> rows(min(numRows, int(s.size())));//當前的行int curRow = 0;bool goingDown = false;for (char c : s) {rows[curRow] += c;//注意這里關于二維數組的判斷條件if (curRow == 0 || curRow == numRows - 1) goingDown = !goingDown;curRow += goingDown ? 1 : -1;}string ret;for (string row : rows) ret += row;return ret;}
};
鏈接:https://leetcode-cn.com/problems/zigzag-conversion/solution/z-zi-xing-bian-huan-by-leetcode/
總結
以上是生活随笔為你收集整理的算法:z字型变换的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。