2 回答

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 的實現方式,但它是對您的解決方案的最小修復。
就個人而言,我會使用字典將字母映射到摩爾斯電碼,然后遍歷字符串中的字符。

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();
}
}
添加回答
舉報