LeetCode 6. ZigZag Conversion
一、 問題描述:
The string "PAYPALISHIRING"
is written in a zigzag pattern on a given number of rows likethis: (you may want to display this pattern in a fixed font for betterlegibility)
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 conversiongiven a number of rows:
string convert(string s, int numRows);
Example1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I
二、 問題分析:
首先確定ZigZagConversion(Z字轉換)的定義:將給定的字串根據行數先轉換為示例所展示的Z形結構,最後將其逐行讀取構成新的字串。
以example 1為例子:
輸入字串為"PAYPALI SHIRING", 行數為3,所以列出的Z形結構為:
P A H N
A P L S I I G
Y I R
逐行讀取方式:
所以輸出的字串就應為:"PAHNAPLSIIGYIR"
三、 演算法設計:
1、 假定給定字串為S,行數為rows
2、 因為要根據所給的字串羅列出Z形結構,Z形結構可以看成一個二維字元陣列(空白看成是空字元‘’);
3、 因為構造行已知但列未知的二維陣列很難實現,所以可以等價構造出目的二維矩陣的轉置矩陣E;
4、 定義行計數變數num =0、b=0,遍歷字串S,執行以下操作:
a) 若行b為0,即第一行,則將E[num]整行填充rows個字元;
b) 若行b不為0,則對應的將E的第num行第rows-b-1個元素,即E[num][rows-b]填充字元,其餘元素填充空字元
c) b = b+1, num = num+1
5、 對E按行優先進行字串遍歷,獲得的字串即為目的字串
四、 程式實現:
class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
s = list(s)
arr = []
h = 0
num = 0
a = 0
newstr = []
while(num < len(s)):
row = ['' for a in range(numRows)]
if(a==0 or a==numRows-1):
for b in range(numRows):
if(num < len(s)):
row[b] = s[num]
num+=1
else:
row[numRows-1-a] = s[num]
num += 1
a = (a + 1)%numRows
if(a==numRows-1):
a = 0
h += 1
arr.append(row)
for a in range(numRows):
for b in range(h):
if(arr[b][a]!=''):
newstr.append(arr[b][a])
return ''.join(newstr)
相關文章
- leetcode ZigZag ConversionLeetCode
- Leetcode 6 ZigZag ConversionLeetCode
- ZigZag Conversion leetcode javaLeetCodeJava
- LeetCode OJ : 6 ZigZag ConversionLeetCode
- LeetCode T6 ZigZag ConversionLeetCode
- (字串)ZigZag Conversion字串
- LeetCode ZigZag Conversion(006)解法總結LeetCode
- LeetCode6: ZigZag Conversion(Z字形變換)LeetCode
- Leetcode Binary Tree Zigzag Level Order TraversalLeetCode
- Leetcode-binary Tree Zigzag Level Order TraversalLeetCode
- [LeetCode] ZigZag Converesion 之字型轉換字串LeetCode字串
- Binary Tree ZigZag Level Order Traversal leetcode javaLeetCodeJava
- Leetcode——6. Z 字形變換LeetCode
- BITMAP CONVERSION TO ROWIDS
- zigzag走線原理及應用
- 6.變數變數
- bitmap conversion from rowids
- Bootstrap系列 -- 6. 列表boot
- 6. 盒子模型模型
- 6.類和物件物件
- what is conversion exit defined in ABAP domainAI
- Again, a chinese char conversion problemAI
- WoW - Today last chance for conversion AccountAST
- 6. JavaScript this指向相關JavaScript
- 6. Git工作流Git
- 6.用on繫結事件事件
- Conversion to Dalvik format failed: Unable to execute dexORMAI
- ADC and DAC Analog Filters for Data ConversionFilter
- 6. vue元件詳解(一)Vue元件
- 6. PLSQL 編寫規範SQL
- 【Vue】6. v-model指令Vue
- 6. CSS常見樣式CSS
- 6.自定義圖片剪下
- PostgreSQL DBA(98) - PG 12 Faster float conversion to textSQLAST
- BITMAP CONVERSION FROM ROWIDS 適用場景
- oracle sql hint提示_BITMAP CONVERSION FROM ROWIDSOracleSQL
- 【重溫基礎】6.數字
- 6. 整合學習&隨機森林隨機森林