6 ZigZig Conversion [M] Z-shaped transform

topic

Given a string, the specified number of lines, to down, from left to right from the Z-shaped arrangement.
For example:

Input: s= "ABCDEFGHIJKLMNOP",  numRows = 4,
Output:AGMBFHLNCEIKODJP
Explanation:
           A    G    M
           B  F H  L N
           C E  I K  O
           D    J    P

Ideas:

First string \ (S \) Z-word aligned, then the character row read. The Z-divided into three in the lower part, an example of a Z: ABCD, in: EF, lower: GHIJ. Law analysis which can be found for the specified number of rows \ (n-\) , the middle number is \ (2-n-\) , each of the upper + as a cycle, the cycle of \ (t = n + 2-n-\) . Then there
line. 1: \ (S [0], S [T + 0], S [0 + 2 \ CDOT T], \ cdots; \)
Line 2: \ (S [. 1], S [0+ T-. 1], S [. 1 + T], \ cdots; \)
\ (\ cdots \)
of \ (\) n- line: \ (S [n--. 1], S [n--. 1 + T], S [n-1 + 2 \ cdot t] \ cdots. \)

Code:

  • C++
class solution{
public:
  string convert(string s, int numRows){
    if(s.size()==1) return s;
    string resString;
    int stringLen=s.size();
    int cycleLen=2*numRows-2;

    for(int i=0;i<numRows;i++){
      for(int j=0;j+i<stringLen;j+=cycleLen){
        resString += s[i+j];
        if(i !=0 && i != numRows-1 && j+cycleLen-i < stringLen){
         resString+=s[j + cycleLen - i];
      }
    }
    return resString;
  }
};
  • python
def covert

Guess you like

Origin www.cnblogs.com/Jessey-Ge/p/10993428.html