Java_唯一摩尔斯密码词(uniqueMorseRepresentations)
题目
思路
//创建morse数组,morseWords数组
//遍历words数组,遍历字符,与Morse匹配,StringBuilder拼接,存入morseWords数组
//遍历morseWords数组,与该元素之前元素对比,如果不重复,统计出现次数+1
class Solution {
public int uniqueMorseRepresentations(String[] words) {
String[] morse = {
".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--",
"-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." };
String[] morseWords=new String[words.length];
for(int i=0;i<words.length;i++) {
StringBuilder sb=new StringBuilder();
for(int j=0;j<words[i].length();j++) {
sb.append(morse[words[i].charAt(j)-'a']);
}
morseWords[i]=sb.toString();
}
int count=0;
for(int i=0;i<morseWords.length;i++) {
boolean flag=false;
for(int j=0;j<i;j++) {
if(morseWords[j].equals(morseWords[i])) {
flag=true;
break;
}
}
if(flag) {
continue;
}
count++;
}
return count;
}
}
测试结果
还没有评论,来说两句吧...