Leetcodes Solutions 6 ZigZag Conversion

匯總

雪之下雪乃:leetcode解題總匯?

zhuanlan.zhihu.com圖標

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 NA P L S I I GY 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".

思路1

直接利用ZigZag的數學特性

class Solution {public: string convert(string s, int numRows) { string result=""; if(numRows==1) return s; int step1,step2; int len=s.size(); for(int i=0;i<numRows;++i){ step1=(numRows-i-1)*2; step2=(i)*2; int pos=i; if(pos<len) result+=s.at(pos); while(1){ pos+=step1; if(pos>=len) break; if(step1) result+=s.at(pos); pos+=step2; if(pos>=len) break; if(step2) result+=s.at(pos); } } return result; }};

推薦閱讀:

講道理,編程到底該學些什麼?
漫談C指針(1):指針背後的邏輯
Matplotlib設計的基本邏輯
如何提高UG曲面造型的水平呢?你都有什麼技巧,一起來看看我的吧
全新的編程入門課程(基於 Python 語言)相關信息公告

TAG:演算法 | 數據結構 | 編程 |