LeetCode OJ : 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 RAnd 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"
.
這個例子分為了三行,所以需要三個string物件來儲存每一行的字串,最後按順序(從第一排到最後一排)將字串相加起來;這個求和之後的字串就是所求,將它返回;
把變換之後的看成是一個週期變化的,第一個週期 P-A-Y-P,第二個週期A-L-I-S,第三個週期....
每個週期又有規律可循,P-A-Y分別存放在0-1-2行;接下來的p存放在1行;然後又是下一個週期。。。。
比如是四排的時候;
第一個週期A-B-C-D-E-F;首先將A-B-C-D存放在0-1-2-3排,再將E-F存放在2-1排。。所以存放在不同排的順序應該是0-1-2-3-2-1;
所以A-B-C-D-E-F對應存放在0-1-2-3-2-1;
每2 * numRows-2個字元依次存放在0-1-2-....-(numRows-1)-(numRows-2)-......--1;
class Solution {
public:
string convert(string s, int numRows) {
vector<string> vstr(numRows);
int i = 0, j = 0;
if(s.size() == 0){
return s;
}
for (i = 0; i < s.size(); ){
for (j = 0; j < numRows; ++j){
if(i == s.size()){
break;
}
vstr[j].push_back(s[i++]);
}
for (j = numRows-2; j >=1 ; --j){
if(i == s.size()){
break;
}
vstr[j].push_back(s[i++]);
}
if(i == s.size()){
string str;
for (i = 0; i < numRows; ++i){
str += vstr[i];
}
return str;
}
}
}
};
執行效率比較低,不過這個執行時間不穩定,第一次提交的時候是22/%。。
相關文章
- Leetcode 6 ZigZag ConversionLeetCode
- LeetCode 6. ZigZag ConversionLeetCode
- LeetCode T6 ZigZag ConversionLeetCode
- leetcode ZigZag ConversionLeetCode
- ZigZag Conversion leetcode javaLeetCodeJava
- LeetCode6: ZigZag Conversion(Z字形變換)LeetCode
- (字串)ZigZag Conversion字串
- LeetCode ZigZag Conversion(006)解法總結LeetCode
- LeetCode OJ : 1 Two SumLeetCode
- Leetcode Binary Tree Zigzag Level Order TraversalLeetCode
- Leetcode-binary Tree Zigzag Level Order TraversalLeetCode
- [LeetCode] ZigZag Converesion 之字型轉換字串LeetCode字串
- Binary Tree ZigZag Level Order Traversal leetcode javaLeetCodeJava
- LeetCode OJ : 2 Add Two NumbersLeetCode
- LeetCode OJ : 5 Longest Palindromic SubstringLeetCode
- LeetCode OJ : 3 Longest Substring Without Repeating CharactersLeetCode
- OJ搭建
- BITMAP CONVERSION TO ROWIDS
- zigzag走線原理及應用
- bitmap conversion from rowids
- what is conversion exit defined in ABAP domainAI
- Again, a chinese char conversion problemAI
- C/C++程式訓練6---歌德巴赫猜想的證明 (sdut oj)C++
- Vue + Koa 搭建 ACM OJVueACM
- 分段函式 (sdut oj)函式
- 計算題 (sdut oj)
- 個人OJ免費搭建
- 畢業旅行 oj題
- 信奧OJ的搭建
- WoW - Today last chance for conversion AccountAST
- Leetcode——6. Z 字形變換LeetCode
- LeetCode 6.Z字形變換LeetCode
- 力扣oj-字串相乘力扣字串
- OJ題之氣泡排序排序
- Hydro OJ搭建全過程
- Conversion to Dalvik format failed: Unable to execute dexORMAI
- ADC and DAC Analog Filters for Data ConversionFilter
- 二叉排序樹 oj 2482排序