leetcode第6题——*ZigZag Conversion

25 篇文章 0 订阅
25 篇文章 0 订阅

题目

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)

P   A   H   N
A P L S I I G
Y   I   R
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 text, int nRows);
convert("PAYPALISHIRING", 3)  should return  "PAHNAPLSIIGYIR" .

思路

简单解释一下zigzag,就是把字符串原顺序012345……按下图所示排列并按行输出:


发现每一行中除斜行的字符其对应的下标为(0,1,2,3,6,7,8,9...),观察得到下标周期cycle=2*(numRows-1),如当numRows=4时,周期为6;而那几个处于斜行的字符,记前一个竖行的字符其下标为j,则斜行字符其下标为j+cycle-2*i,其中i为对应的行下标(0,1,2,...,numRows-1)。找到每一行的下标规律,按照字符串相加即可得到所求字符串。

代码

Python
class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        cycle = 2*(numRows - 1)
        strLen = len(s)
        res = ''
        if (strLen == 0) | (numRows < 2):
            return s
        for i in range(numRows):
            for j in range(i,strLen,cycle):
                res += s[j]
                if (i > 0) & (i < numRows - 1):
                    #首行和最后一行除外的其他要再加一个元素,下标为j + cycle - 2*i
                    zIndex = j + cycle - 2*i
                    if (zIndex < strLen):
                        res += s[zIndex]
        return res
Java
public class Solution {
    public String convert(String s, int numRows) {
       int strLen = s.length();
       if (numRows < 2 || strLen == 0)
    	   return s;
       int cycle = 2*(numRows - 1);
       String res = "";
       for(int i = 0;i < numRows;i++){
    	   for(int j = i;j < strLen;j += cycle){
    		   res += s.charAt(j);
    		   //除开首行和最后一行的其他行再添加s[index],index = j+2*(numRows-1)-2*i
    		   if(i > 0 && i < numRows-1){
    			   int zIndex = j + cycle - 2*i;
    			   if(zIndex < strLen)
    				   res += s.charAt(zIndex);
    		   }
    	   }
       }
       return res;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值