Java_唯一摩尔斯密码词(uniqueMorseRepresentations)

系统管理员 2023-06-02 09:12 95阅读 0赞

题目
在这里插入图片描述
思路

//创建morse数组,morseWords数组
//遍历words数组,遍历字符,与Morse匹配,StringBuilder拼接,存入morseWords数组
//遍历morseWords数组,与该元素之前元素对比,如果不重复,统计出现次数+1

  1. class Solution {
  2. public int uniqueMorseRepresentations(String[] words) {
  3. String[] morse = {
  4. ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--",
  5. "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." };
  6. String[] morseWords=new String[words.length];
  7. for(int i=0;i<words.length;i++) {
  8. StringBuilder sb=new StringBuilder();
  9. for(int j=0;j<words[i].length();j++) {
  10. sb.append(morse[words[i].charAt(j)-'a']);
  11. }
  12. morseWords[i]=sb.toString();
  13. }
  14. int count=0;
  15. for(int i=0;i<morseWords.length;i++) {
  16. boolean flag=false;
  17. for(int j=0;j<i;j++) {
  18. if(morseWords[j].equals(morseWords[i])) {
  19. flag=true;
  20. break;
  21. }
  22. }
  23. if(flag) {
  24. continue;
  25. }
  26. count++;
  27. }
  28. return count;
  29. }
  30. }

测试结果
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,95人围观)

还没有评论,来说两句吧...

相关阅读