第一次看到这道题,恍惚之间以为回到了儿童时期在做数学卷子。这tm就是个小学奥数题吧。
然后面对这个小学奥数题,我花费了一个下午(顺路刷完了毒奶粉账号的疲劳);
虽然花费的时间比较多但是提交之后发现又是一个超过百分之百的,感觉心情还不错。
代码如下:
static const auto io_speed_up = []() { std::ios::sync_with_stdio(false); cin.tie(nullptr); return 0; }(); class Solution { public: string convert(string s, int numRows) { if (numRows == 1) return s; int length = s.size(); int groupNum = numRows + numRows - 2; bool isShort = false; if (groupNum > length) { s = s + string(groupNum - length, '0'); length = groupNum; isShort = true; } int quotient = length / groupNum; int remainder = length % groupNum; vector<int> num(groupNum); vector<int> sum(numRows); int i = 0; int j = 0; for (i = 0; i < remainder; ++i) num[i] = 1; sum[1] = quotient + num[0]; for (int i = 2; i < numRows; ++i) { j = i - 1; sum[i] = sum[j] + quotient + quotient + num[j] + num[groupNum - j]; } i = 0; j = 0; int group = 0; int doubleRow = numRows - 1; string res(s); while (group < quotient) { res[sum[0]++] = s[i++]; j = 1; while(j < doubleRow) res[sum[j++]++] = s[i++]; res[sum[doubleRow]++] = s[i++]; while(j > 1) res[sum[--j]++] = s[i++]; ++group; } j = 0; int k = 0; while(j < doubleRow && k++ < remainder) res[sum[j++]++] = s[i++]; if (i < length) { res[sum[doubleRow]++] = s[i++]; ++k; } while(j > 1 && k++ < remainder) res[sum[--j]++] = s[i++]; if (isShort) { char* temp = new char[length]; for (i = 0, j = 0; i < length; ++i) { if(res[i] != '0') temp[j++] = res[i]; } temp[j] = '