Unique Morse code word
1. C++ practice
class Solution { public: int uniqueMorseRepresentations(vector<string>& words) { string morse[]={".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."}; set<string> res; for(int i=0;i<words.size();i++){ string tmp=""; string cur=words[i]; for(int j=0;j<cur.length();j++){ tmp+=morse[cur[j]-'a'];//'a' is 97 'z' is 122 Convert the character number to the numeric number b-'a' is 98-97=1 a-'a ' is 97-97=0 } res.insert(tmp); } return res.size();//Map deduplication } };
2.java practice
class Solution { public int uniqueMorseRepresentations(String[] words) { String[] morseCode= {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."}; HashSet<String> set=new HashSet<>(); for(String word:words){//String in java should be capitalized String code=""; for(char c:word.toCharArray())//toCharArray() converts a string to a character array code +=morseCode[c-'a']; set.add(code); } return set.size();//According to HashSet, duplicate elements cannot be placed } }
3. python practice
class Solution: def uniqueMorseRepresentations(self, words): d = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] return len({''.join(d [ord(i)-ord('a')]for i in w) for w in words})Whether you can read it or not, it feels a little clear, so write it down first and learn python well