|
76 | 76 | },
|
77 | 77 | {
|
78 | 78 | "cell_type": "code",
|
79 |
| - "execution_count": 1, |
| 79 | + "execution_count": 49, |
80 | 80 | "metadata": {},
|
81 | 81 | "outputs": [
|
82 | 82 | {
|
83 | 83 | "data": {
|
84 | 84 | "text/plain": [
|
85 |
| - "[['tea', 'ate', 'tan'], ['ate'], ['nat'], ['bat']]" |
| 85 | + "[['tan', 'nat'], ['eat', 'tea', 'ate'], ['bat']]" |
86 | 86 | ]
|
87 | 87 | },
|
88 |
| - "execution_count": 1, |
| 88 | + "execution_count": 49, |
89 | 89 | "metadata": {},
|
90 | 90 | "output_type": "execute_result"
|
91 | 91 | }
|
92 | 92 | ],
|
93 | 93 | "source": [
|
94 | 94 | "### Leetcode 49\n",
|
95 | 95 | "\n",
|
96 |
| - "strs = [\"eat\",\"tea\",\"tan\",\"ate\",\"nat\",\"bat\"]\n", |
97 |
| - "\n", |
98 |
| - "l = []\n", |
99 |
| - "ll = []\n", |
100 |
| - "a = 0\n", |
101 |
| - "b = a + 1\n", |
102 |
| - "while a != len(strs):\n", |
103 |
| - " if a == len(strs) - 1:\n", |
104 |
| - " ll.append([strs[a]])\n", |
105 |
| - " break\n", |
106 |
| - "\n", |
107 |
| - " elif sorted(strs[a]) == sorted(strs[b]):\n", |
108 |
| - " l.append(strs[b])\n", |
109 |
| - " strs.remove(strs[a])\n", |
110 |
| - "\n", |
111 |
| - " b += 1\n", |
112 |
| - "\n", |
113 |
| - " if b == len(strs):\n", |
114 |
| - " l.append(strs[a])\n", |
115 |
| - " ll.append(l)\n", |
116 |
| - " l = []\n", |
| 96 | + "class Solution(object):\n", |
| 97 | + " def groupAnagrams(self, strs):\n", |
| 98 | + " \"\"\"\n", |
| 99 | + " :type strs: List[str]\n", |
| 100 | + " :rtype: List[List[str]]\n", |
| 101 | + " \"\"\" \n", |
117 | 102 | "\n",
|
118 |
| - " a += 1\n", |
119 |
| - " b = a + 1\n", |
| 103 | + " hash = {j:[] for j in set([''.join(sorted(i)) for i in strs])}\n", |
120 | 104 | "\n",
|
121 |
| - "ll\n", |
| 105 | + " for i in strs:\n", |
| 106 | + " hash[''.join(sorted(i))].append(i)\n", |
122 | 107 | "\n",
|
123 |
| - " " |
| 108 | + " return list(hash.values())\n" |
124 | 109 | ]
|
125 | 110 | }
|
126 | 111 | ],
|
|
0 commit comments