兩種路子
1.
class Solution {
public:
string convert(string s, int numRows) {
if (numRows == 1) return s;
vector<string> rows(min(numRows, int(s.size()))); // 防止s的長度小於行數
int curRow = 0;
bool goingDown = false;
for (char c : s) {
rows[curRow] += c;
if (curRow == 0 || curRow == numRows - 1) {// 當前行curRow爲0或numRows -1時,箭頭髮生反向轉折
goingDown = !goingDown;
}
curRow += goingDown ? 1 : -1;
}
string ret;
for (string row : rows) {// 從上到下遍歷行
ret += row;
}
return ret;
}
};
這種方法是採用vector<string>對字符串按照numRows的步長從上到下在從下到上遍歷一遍,之後重複操作,直到遍歷完字符串,之後在把vector<string>中的字符串粘貼到一個新的String類型中就可以了
2.
string convert(string s, int numRows) {
if (numRows == 1) return s;
int step = numRows * 2 - 2; // 間距
int index = 0;// 記錄s的下標
int len = s.length();
int add = 0; // 真實的間距
string ret;
for (int i = 0; i < numRows; i++) // i表示行號
{
index = i;
add = i * 2;
while (index < len)//超出字符串長度計算下一層
{
ret += s[index]; // 當前行的第一個字母
add = step - add;// 第一次間距是step -2*i,第二次是2*i,
index += (i == 0 || i == numRows-1) ? step : add; // 0行和最後一行使用step間距,其餘使用add間距
}
}
return ret;
}
這種方法是找到每個行之間的關係是來進行輸入的