zoukankan      html  css  js  c++  java
  • 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  
    
  • 相关阅读:
    Yii2 的 updateAll 方法参数详解
    Yii2 数据库查询汇总
    Git常见报错
    git rebase篇
    在 Yii 2.0 上,使用 updateAll() 更新表列值为同一表的另一列值的实现
    Git从其他分支merge个别文件
    Git cherry-pick 复制多个commit
    Git 删除某次提交(某个commit)的方法
    多进程记录
    python3安装Crypto过程
  • 原文地址:https://www.cnblogs.com/Jessey-Ge/p/10993428.html
Copyright © 2011-2022 走看看