0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

LeetCode 6. Zigzag Conversion の回答

Posted at

初めに

今回もLeetCodeを解いていこうかと思います。
問題文は以下

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
Example 3:

Input: s = "A", numRows = 1
Output: "A"
 

Constraints:

1 <= s.length <= 1000
s consists of English letters (lower-case and upper-case), ',' and '.'.
1 <= numRows <= 1000

回答

私の回答は以下

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        final_value = ""
        final_dict = {}
        if numRows >1 :
            result = [s[i:i+numRows-1] for i in range(0, len(s), numRows-1)]
        else:
            return s
        for i, ss in enumerate(result):
            even_key = 1
            odds_key = numRows
            if i % 2 == 0:
                for s in ss:
                    if even_key in final_dict:
                        final_dict[even_key] += s  # すでにある値の後ろに追加
                    else:
                        final_dict[even_key] = s
                    even_key += 1
            else:
                for s in ss:
                    if odds_key in final_dict:
                        final_dict[odds_key] += s  # すでにある値の後ろに追加
                    else:
                        final_dict[odds_key] = s
                    odds_key -= 1

        for i, s in final_dict.items():
            final_value += s

        return final_value 

nowRowsの個数に合わせて文字列を分割して、その中でdictに保存する方法を偶数個目のグループと奇数個目のグループで分けてみることで対応しました。
中々難しかった。。あとコード長い笑

最後に

もっといい方法あれば教えていただきたいです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?