6. Z-Shape Transformation Title Description
Arranges the string "paypalishiring" in a Z-glyph to the given number of rows:
P a H N
A P L S i i G
Y i R
Then, from left to right, read the character by line: "Pahnaplsiigyir"
Implements a function that transforms a string into a specified number of rows:
String Convert (string s, int numrows);
Example 1:
Input: s = "paypalishiring", NumRows = 3
output: "Pahnaplsiigyir"
Example 2:
Input: s = "paypalishiring", NumRows = 4
output: "Pinalsigyahrpi"
Explanation:
P i N
A L s i G
Y a< C9/>h R
P I
String
C
#include <bits/stdc++.h> using namespace std;
/******************** Commit Code ********************/char* convert (char* s, int numrows) {if (numrows==1) return s;//special handling 1
int N=strlen (s), i=0,cnt=0;
int x=4+2* (numRows-3), y=0,z=0,t=0;
BOOL flag=true;//x and Y are not 0 o'clock true fetch x,false take y char *ans= (char*) malloc ((n+1) *sizeof (char));
for (; i<numrows; ++i) {ans[cnt++]=s[i];
t=i;
while (true) {if (flag) z=x;
else z=y;
if (x==0)//special handling the first line and the last line z=y;
else if (y==0) z=x;
if (t+z>=n) break;//jump out of condition ans[cnt++]=s[t+z];
Flag=!flag;
T+=z;
} x-=2,y+=2,z=0;
Flag=true;
} ans[cnt]= ' + ';
return ans; }/***************************************************/int Main () {#ifdef Online_judge #else freopen ("F:/cb/read.txt
"," R ", stdin); Freopen ("F:/cb/out.txt", "w", StdouT);
#endif Ios::sync_with_stdio (FALSE);
Cin.tie (0);
Char s[1000],ss[10];
while (Cin.getline (s,1000)) {int numrows;
cin>>numrows;
cout<<s<<endl;
cout<<numrows<<endl;
cout<< "/" <<convert (s,numrows) << "/" <<endl;
Cin.getline (ss,10);//Eat carriage return} return 0; }
As a rule to do.
Subscript into a number after the Z-type is arranged as follows:
When numrows=3:
The number of the first line differs by 4;
The difference between the second row of numbers is 2;
The third row of numbers differs by 4.
When numrows=4:
The number of the first line differs by 6;
The difference between the second row of numbers is 4, 2;
The third row of numbers differs by 2, 4.
The four-row number differs by 6.
When numrows=5:
The number of the first line differs by 8;
The difference between the second row of numbers is 6, 2;
The third row of numbers differs by 4, 4.
The difference between the four numbers is 2, 6;
There is a difference of 8 between the five digits.
................ Divider line ....... ...........
According to the given number of rows, by line traversal, find the law found that the first and last line difference is 4+2* (numRows-3)
Look vertically, two difference between each line 2
X and y represent the difference between the two neighbors of a row (to maintain consistency, the first and last lines add 0)
Alternately take x and Y, mark the current x or Y with the flag flag