题目
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 s, int numRows);
- Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
- Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I
优秀代码###
class Solution:
def convert(self, s, numRows):
if numRows == 1 or numRows >= len(s): return s
row, direction, res = 0, -1, [""] * numRows
for char in s:
res[row] += char
if row == 0 or row == numRows - 1: direction *= -1
row += direction
return "".join(res)
反例代码
def convert(s,num):
b = []
c = ''
i = 0
while i<len(s):
x = -2
for t in range(0,num+num-2):
if i+t<len(s):
if t > num -1:
b[x] += s[i+t]
x -= 1
continue
if t > len(b) - 1:
b.append('')
b[t] += s[i+t]
i += (num + num - 2)
print(b)
for a in b:
c += a
return c
print(convert('A',3))
代码对比
第二个答案的精妙之处在于引入的中间变量step可以变为-1,这样极为简单,
如果计算复杂度,可以发现第一个答案有3个循环,第二个答案有一个循环,第一个是n^2+n ,第二个是n
Time limited
刷LeetCode好多次遇到time limited这样的问题,这样就是时间复杂度太高了,那么如何计算复杂度呢,如何降低复杂度呢?
首先了解一下几个概念。一个是时间复杂度,一个是渐近时间复杂度。前者是某个算法的时间耗费,它是该算法所求解问题规模n的函数,而后者是指当问题规模趋向无穷大时,该算法时间复杂度的数量级。
当我们评价一个算法的时间性能时,主要标准就是算法的渐近时间复杂度,因此,在算法分析时,往往对两者不予区分,经常是将渐近时间复杂度T(n)=O(f(n))简称为时间复杂度,其中的f(n)一般是算法中频度最大的语句频度。