2 回答
![?](http://img1.sycdn.imooc.com/5458463b0001358f02200220-100-100.jpg)
TA贡献1777条经验 获得超3个赞
问题是您首先遍历 zip_,然后遍历字母。这就是导致字母顺序的原因—— zip_ 按字母顺序排序。
这个版本做你想让它做的事:
class Solution:
def uniqueMorseRepresentations(self, words: List[str]) -> int:
morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
transformation = []
zip_ = list(zip(morse, alphabet))
for word in words:
transformation.append(''.join(code[0] for letter in word for code in zip_ if letter in code[1]))
这不是最 Pythonic 的实现方式,但它是对您的解决方案的最小修复。
就个人而言,我会使用字典将字母映射到摩尔斯电码,然后遍历字符串中的字符。
![?](http://img1.sycdn.imooc.com/533e50ed0001cc5b02000200-100-100.jpg)
TA贡献1858条经验 获得超8个赞
不确定您面临的问题,但这会过去:
class Solution:
def uniqueMorseRepresentations(self, words):
morse_map = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--",
"-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."]
return len({''.join(morse_map[ord(char) - 97] for char in word) for word in words})
97 是ord('a'):
class Solution:
def uniqueMorseRepresentations(self, words):
morse_map = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--",
"-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."]
return len({''.join(morse_map[ord(char) - ord('a')] for char in word) for word in words})
我没有在您的解决方案中看到return声明或 a set()。有两个简单的步骤:
将访问过的转换添加到集合中
返回集合的长度
set()如果您有兴趣,这里还有一个使用 HashSet 的 Java 版本(类似于Python 中的):
public final class Solution {
public static final int uniqueMorseRepresentations(
final String[] words
) {
final String[] morseMap = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."};
Set<String> transformations = new HashSet<>();
for (String word : words) {
StringBuilder transformation = new StringBuilder();
for (int index = 0; index < word.length(); index++)
transformation.append(morseMap[word.charAt(index) - 97]);
transformations.add(transformation.toString());
}
return transformations.size();
}
}
添加回答
举报