將一個給定字符串 s 根據(jù)給定的行數(shù) numRows ,以從上往下、從左到右進行 Z 字形排列。
比如輸入字符串為 "PAYPALISHIRING" 行數(shù)為 3 時,排列如下:
P A H N
A P L S I I G
Y I R
之后,你的輸出需要從左往右逐行讀取,產(chǎn)生出一個新的字符串,比如:"PAHNAPLSIIGYIR"。
題目理解如下圖所示:形狀相當(dāng)于將Z字先向右鏡像在順時針旋轉(zhuǎn)90度

思路:
1)用vector容器來創(chuàng)建字符串?dāng)?shù)組;
2)對字符串s進行遍歷,用vector數(shù)組按照Z字形變換來存儲s中的單個字符。具體操作請看代碼;
3)遍歷輸出vector字符串?dāng)?shù)組。
補充知識點:
bool類型的數(shù)據(jù)在進行加減法操作時,當(dāng)它為false,其值為0;當(dāng)它為true,其值為1。
string convert(string s, int numRows) {
int len = s.size();
if(numRows == 1) //如果numRows為1,則直接返回s。
return s;
string res = "";
vector<string> rows(min(len, numRows)); /*用vector容器創(chuàng)建字符串?dāng)?shù)組rows用來存儲各個子串。
rows[cur]表示第cur個子串,
rows[cur][i]表示第cur個子串的第i個字符 cur和i都是從0開始*/
bool goingdown = false; /*goingdown的作用是用于反轉(zhuǎn)的,當(dāng)cur為0或numRows-1時,這是就需要反轉(zhuǎn)了。*/
int cur = 0;
for(char c: s){ //遍歷s中的每個字符c
rows[cur] += c; //存儲字符串
if(0 == cur || numRows-1 == cur) //當(dāng)cur為0或numRows-1時,這是就需要反轉(zhuǎn)了
goingdown = !goingdown;
cur += goingdown? 1:-1; //當(dāng)goingdown為true,cur+= 1,當(dāng)goingdown為false,cur+= -1
}
for(string r : rows) //遍歷rows中的每個字符串
res += r;
return res;
}