唯一摩斯密码词
1.c++做法
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'为97 'z'为122 将字符型数转换为数值型数 b-'a'就是98-97=1 a-'a'就是97-97=0
}
res.insert(tmp);
}
return res.size();//映射去重
}
};
2.java做法
class Solution {
public int uniqueMorseRepresentations(String[] words) {
String[] morseCode= {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
HashSet<String> set=new HashSet<>();
for(String word:words){//java中的String要大写
String code="";
for(char c:word.toCharArray())//toCharArray() 将字符串转换为字符数组
code +=morseCode[c-'a'];
set.add(code);
}
return set.size();//也是根据HashSet不能放入重复元素
}
}
3.python做法
class Solution:
def uniqueMorseRepresentations(self, words):
d = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
return len({''.join(d [ord(i)-ord('a')]for i in w) for w in words})
不管看不看得懂,感觉有点明白,先写下来,好好学python