【LeetCode】6.Z 字形变换
生活随笔
收集整理的這篇文章主要介紹了
【LeetCode】6.Z 字形变换
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
6.Z 字形變換
我的思路貌似沒有第二家,不過(guò)我懶得解釋了。
#include <string> #include <iostream> using namespace std;template<typename T> T ConvertZ(const T& vec, int N) {if (N <= 1)return vec;T ret;int n = N - 1;int n2 = n * 2;int length = vec.size();ret.resize(length);//組數(shù)-1int m = length / n2;//最后一組的元素?cái)?shù)量 [0, 2n)int other = length - m * n2;//最后一組的每行元素?cái)?shù)量(一共N行)int* last = new int[N]();//首尾行特殊判斷if (other > 0){last[0] = 1;if (other > n){last[n] = 1;}}//其余行for (int i = 1; i != N; ++i){if (i < other)last[i] += 1;if (n2 < other + i)last[i] += 1;}//第n行前的數(shù)量求和for (int i = 0; i != N; ++i){last[i] += m;//組數(shù)//第一行和最后一行只加mif (i != 0 && i != n)last[i] += m;if (i > 0)last[i] += last[i - 1];}for (int i = 0; i != length; ++i){//余數(shù)int mu = i % n2;//組號(hào)int div = i / n2;if (mu == 0){ret[div] = vec[i];}else if (mu == n){ret[last[n - 1] + div] = vec[i];}else if (mu < n){ret[last[mu - 1] + div * 2] = vec[i];}else if (mu > n){ret[last[n2 - mu - 1] + div * 2 + 1] = vec[i];}}delete[] last;return ret; }int main() {wcout << L"---------------------string is------------------------" << endl;wstring str0 = L"PAYPALISHIRING";wcout << str0 << L" -> " << ConvertZ(str0, 3) << " should be \"PAHNAPLSIIGYIR\"" << endl;wcout << str0 << L" -> " << ConvertZ(str0, 4) << " should be \"PINALSIGYAHRPI\"" << endl; }?
總結(jié)
以上是生活随笔為你收集整理的【LeetCode】6.Z 字形变换的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【LeetCode】5.最长回文子串
- 下一篇: 【DirectX12】1.基本组件创建和