【leetcode】ZigZag Conversion
題目簡(jiǎn)述
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".
解題思路:
這個(gè)題目有兩種做法:第一種是模擬,也就是說我們可以有幾行就開幾個(gè)數(shù)組都存起來,最后合到一起就可以了;另一種方法是找規(guī)律。因?yàn)榈谝环N比較直觀,故代碼實(shí)現(xiàn)了第一種思路:
class Solution:# @return a stringdef convert(self, s, nRows):if nRows == 1:return sgap = nRows - 2res = []for i in range(nRows):res.append([])i = 0while i < len(s):for j in range(nRows):if i >= len(s):breakres[j] += s[i]i += 1for j in range(gap,0,-1):if i >= len(s):breakres[j] += s[i]i += 1ress = ""for i in res:for j in i:ress += jreturn ress轉(zhuǎn)載于:https://www.cnblogs.com/MrLJC/p/4437530.html
總結(jié)
以上是生活随笔為你收集整理的【leetcode】ZigZag Conversion的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 全国计算机等级考试题库二级C操作题100
- 下一篇: 全国计算机等级考试题库二级C操作题100