题目来源
题目描述
题目解析
暴力模拟
class Solution {
private static final String[] mi = new String[]{".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
public int uniqueMorseRepresentations(String[] words) {
Set<String> set = new HashSet<>();
String f = "";
for (String s: words){
char[] carr = s.toCharArray();
for (char c : carr){
int i = c - 'a';
f = f + mi[i];
}
if (!set.contains(f)){
set.add(f);
}
f = "";
}
return set.size();
}
}
优化
private static final String[] mi = new String[]{".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
public static int uniqueMorseRepresentations(String[] words) {
Set<String> set = new HashSet<>();
for (String s: words){
char[] carr = s.toCharArray();
StringBuilder f = new StringBuilder();
for (char c : carr){
int i = c - 'a';
f.append(mi[i]);
}
// 没有关系,重复会自动去掉
set.add(f.toString());
}
return set.size();
}
- C++:
class Solution {
public:
int uniqueMorseRepresentations(vector<string>& words) {
string Morse[26] = {
".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",
".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",
".--","-..-","-.--","--.."
};
std::set<std::string> set;
for(const auto & word : words){
std::string str;
for(const auto & ch : word){
str += Morse[ch - 'a'];
}
set.insert(str);
}
return set.size();
}
};