鱼C论坛

 找回密码
 立即注册
查看: 2121|回复: 0

[学习笔记] Leetcode 6. ZigZag Conversion

[复制链接]
发表于 2020-9-16 02:58:49 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
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

  1. class Solution:
  2.     def convert(self, s: str, numRows: int) -> str:
  3.         if numRows == 0 or s == None or len(s) == 0:
  4.             return ""
  5.         if numRows == 1:
  6.             return s
  7.         result = ['' for _ in range(numRows)]
  8.         count = 0
  9.         flag = 0
  10.         for i in range(len(s)):
  11.             if flag == 0:
  12.                 result[count] += (s[i])
  13.                 count += 1
  14.                 if count == numRows - 1:
  15.                     flag = 1 - flag
  16.             else:
  17.                 result[count] += (s[i])
  18.                 count -= 1
  19.                 if count == 0:
  20.                     flag = 1 - flag
  21.         return "".join(result)
复制代码

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-25 04:33

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表