力扣6. Z 字形变换
字符串题目,遭罪
题目:【https://leetcode.cn/problems/zigzag-conversion/?envType=study-plan-v2&envId=top-interview-150】
1 class Solution { 2 public: 3 string convert(string s, int numRows) { 4 int len = s.length(); 5 if (len <= 2 || 1 == numRows) 6 return s; 7 8 // string ret(s); 9 string ret(len, 0); 10 int ci = 0; 11 int step = (numRows << 1) - 2; 12 for (int i = 0; i < numRows; ++i) { 13 // cout << "row === " << i << endl; 14 for (int j = 0; ; ++j) { 15 // cout << "j == " << j << endl; 16 int si1 = j * step - i; 17 if (i < numRows - 1 && si1 >= 0 && si1 < len) 18 { /* cout << "ci, si1 = " << ci << ", " << si1 << endl; */ ret[ci] = s[si1]; ci++; } 19 else 20 si1 = -100; 21 22 int si2 = j * step + i; 23 if (si1 != si2 && si2 >= 0 && si2 < len) 24 { /* cout << "ci, si2 = " << ci << ", " << si2 << endl; */ ret[ci] = s[si2]; ci++; } 25 26 if (si2 > len || ci >= len) { 27 // cout << "break" << endl; 28 break; 29 } 30 } 31 } 32 return ret; 33 } 34 };
下面这个好理解,但是时间和空间上都不如自己想的
1 class Solution { 2 public: 3 string convert(string s, int numRows) { 4 int len = s.length(); 5 if (len <= 2 || 1 == numRows) 6 return s; 7 8 string ret; 9 vector<string> cache(numRows); 10 int i = 0; 11 int flag = -1; 12 for (auto c : s) { 13 cache[i] += c; 14 if (0 == i || numRows - 1 == i) 15 flag = -flag; 16 i += flag; 17 } 18 19 for (auto s : cache) 20 ret += s; 21 return ret; 22 } 23 };
浙公网安备 33010602011771号