6 ZigZig Conversion[M]Z字形变换

题目

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:

string convert(string s, int numRows);

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

思路:

先将字符串\(s\)进行Z字排列,再按行读取字符。将Z字分为上中下三个部分,则例子的Z上:ABCD,中:EF,下:GHIJ。分析其规律可以发现,对于指定的行数\(n\),中部的个数为\(n-2\),将每一个上+中作为一个循环,则循环周期为\(t=n+n-2\)。于是有
第1行:\(s[0], s[0+t],s[0+2 \cdot t], \cdots ;\)
第2行:\(s[1], s[0+t-1],s[1+t],\cdots;\)
\(\cdots\)
\(n\)行:\(s[n-1],s[n-1+t],s[n-1+2 \cdot t]\cdots .\)

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

class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        
        if numRows == 1:
            return s
        
        rows = [""]*numRows
        
        cycle = 2*numRows - 2
        result = ""
        
        level = 0 #层数
        aux = -1
        for i in s:
            rows[level] += i
            if(level == 0 or level == numRows -1):
                aux *= -1
            level += aux
        
        for i in rows:
            result += i
                    
        return result  
posted @ 2019-06-09 14:31  风雪初晴,宜下江南  阅读(203)  评论(0编辑  收藏  举报