<style> html, body, .ui-content { background: #222222; color: #00BFFF; } /* 設定 code 模板 */ .markdown-body code, .markdown-body tt { background-color: #ffffff36; } .markdown-body .highlight pre, .markdown-body pre { color: #ddd; background-color: #00000036; } .hljs-tag { color: #ddd; } .token.operator { background-color: transparent; } /* 設定連結 */ a, .open-files-container li.selected a { color: #89FFF8; } a:hover, .open-files-container li.selected a:hover { color: #89FFF890; } </style> ###### tags: `Leetcode` # 6. Zigzag Conversion ###### Link : https://leetcode.com/problems/zigzag-conversion/description/ ## 題目 PAYPALISHIRING 變成 ``` P A H N A P L S I I G Y I R ``` 答案: 由左至右,由上至下 PAHNAPLSIIGYIR ## 程式碼 ```cpp= class Solution { public: string convert(string s, int numRows) { //round:"PAYP", "ALIS", "HIRI", "NG" 每一次最大的大小 const int round = numRows + numRows - 2, strSize = s.size(); if(round == 0) return s; //Char:存放"PAYP", "ALIS", "HIRI", "NG" vector<string> Char; string ans; int k = 0; while(k < strSize){ ans += s[k];//第一層直接放入 Char.push_back(s.substr(k + 1, round - 1)); k += round; } int i = 0; // P A H N (第一層已經放進去) // // A P L S I I G // Y I R // 對應編號 // 0 2 0 2 0 2 0 // 1 1 1 //須走 numRows - 2 次 while(i < numRows - 1){ for(int m = 0;m < Char.size();m++){ //大小不夠放入第 i 個 (Char[m].size() - 1 < i) // unsigned int 避免overflow if(Char[m].size() < i + 1) continue; //最後一次 if(i == numRows - 2){ ans += Char[m][(round - 1) / 2]; continue; } ans += Char[m][i]; //字串大小需大於這次的所需的編號 if(Char[m].size() >= round - 1 - i){ ans += Char[m][round - 2 - i]; } } i++; } return ans; } }; ``` ## Date ### 2023/2/3