|
7808 | 7808 | " "
|
7809 | 7809 | ],
|
7810 | 7810 | "metadata": {
|
7811 |
| - "id": "x9UttcXT7klc", |
7812 |
| - "outputId": "391d3633-0681-4b53-9260-8c0d2c439831", |
7813 | 7811 | "colab": {
|
7814 | 7812 | "base_uri": "https://localhost:8080/"
|
7815 |
| - } |
| 7813 | + }, |
| 7814 | + "id": "x9UttcXT7klc", |
| 7815 | + "outputId": "391d3633-0681-4b53-9260-8c0d2c439831" |
7816 | 7816 | },
|
7817 | 7817 | "execution_count": 50,
|
7818 | 7818 | "outputs": [
|
|
7824 | 7824 | ]
|
7825 | 7825 | }
|
7826 | 7826 | ]
|
| 7827 | + }, |
| 7828 | + { |
| 7829 | + "cell_type": "code", |
| 7830 | + "source": [ |
| 7831 | + "class Solution(object):\n", |
| 7832 | + " def convert(self, s, numRows):\n", |
| 7833 | + " if numRows == 1 or numRows >= len(s):\n", |
| 7834 | + " return s\n", |
| 7835 | + " # This is a vague sentence for python beginers\n", |
| 7836 | + " L = [''] * numRows\n", |
| 7837 | + " # it can be replaced by the following:\n", |
| 7838 | + " # L = []\n", |
| 7839 | + " # for i in range(0, numRows):\n", |
| 7840 | + " # L.append('')\n", |
| 7841 | + " # so if numRows = 3, L = ['', '', '']\n", |
| 7842 | + " index, step = 0, 1\n", |
| 7843 | + "\n", |
| 7844 | + " for x in s:\n", |
| 7845 | + " L[index] += x\n", |
| 7846 | + " # start #\n", |
| 7847 | + " if index == 0:\n", |
| 7848 | + " step = 1\n", |
| 7849 | + " elif index == numRows -1:\n", |
| 7850 | + " step = -1\n", |
| 7851 | + " #1 end #\n", |
| 7852 | + " # I like to explain the part above\n", |
| 7853 | + " # take the str \"PAYPALISHIRING\" for example:\n", |
| 7854 | + " # We start with variable index with the value 0, step with the value 1\n", |
| 7855 | + " # Each row added with the next char\n", |
| 7856 | + " # If we reach the bottommost row, we need to turn to the next above row, so we change the step value to -1\n", |
| 7857 | + " # we keep the step value until we reach topmost row. DON'T CHANGE IT!\n", |
| 7858 | + " # Again, if we reach the topmost row, we need to reset the step value to 1\n", |
| 7859 | + " # What we need to remember is:\n", |
| 7860 | + " # the zigzag pattern is just a pictorial image for us to have a better understanding\n", |
| 7861 | + " # What the trick of algorithm is actually add the next char of the given string to different rows.\n", |
| 7862 | + " # Don't really think how to move the cursor in the matrix.\n", |
| 7863 | + " # It's really misleading way you think of this. Even it works, it's not efficient.\n", |
| 7864 | + " index += step\n", |
| 7865 | + "\n", |
| 7866 | + " return ''.join(L)" |
| 7867 | + ], |
| 7868 | + "metadata": { |
| 7869 | + "id": "SNWpSw99fBLU" |
| 7870 | + }, |
| 7871 | + "execution_count": null, |
| 7872 | + "outputs": [] |
7827 | 7873 | }
|
7828 | 7874 | ],
|
7829 | 7875 | "metadata": {
|
|
0 commit comments