码迷,mamicode.com
首页 > 其他好文 > 详细

6. ZigZag Conversion

时间:2016-05-31 06:30:08      阅读:319      评论:0      收藏: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".

链接:https://leetcode.com/problems/zigzag-conversion/

一刷

python

先算s里有多少波峰,然后两轮循环,外循环为numRows,内循环为波峰数量,每一步均计算左右两侧分别是否valid,每个group波谷的范围为左开右闭。

算法边界条件太多,runtime只beat不到10%

class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if len(s) <= numRows or numRows == 1:
            return s
        num_group = (len(s) + numRows - 1 ) // (2 * (numRows - 1)) + 1
        zigzag_chars = []
        for row in range(numRows):
            for i in range(num_group):
                left_index = 2 * (numRows - 1) * i - row
                right_index = 2 * (numRows - 1) * i + row
                if left_index >= 0 and left_index < len(s):
                    if left_index % (2 * (numRows - 1)) != 0 and left_index % (numRows - 1) == 0:
                        pass
                    else:
                        zigzag_chars.append(s[left_index])
                if left_index != right_index and right_index < len(s):
                    zigzag_chars.append(s[right_index])
        return ‘‘.join(zigzag_chars)

 

6. ZigZag Conversion

标签:

原文地址:http://www.cnblogs.com/panini/p/5544573.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!