leetcode804. Unique Morse cipherword (java)

 public int uniqueMorseRepresentations(String[] words) {
          String[] numberstr = new String[]{".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."};
        Map<Integer, String> morsemap = new HashMap<>();
        Map<String,String>resultmap=new HashMap<>();
        perparenum(numberstr, morsemap);//Store each letter and the corresponding Morse code
        for (int i = 0; i < words.length; i++) {
            String morse=words[i];
            String result = "";
            for(int j=0;j<morse.length();j++){
                int str=morse.charAt(j);
                String strs=morsemap.get(str);
                result+=strs;
            }
            if(resultmap.isEmpty()){
                resultmap.put(morse,result);
            }else{
                if(!resultmap.containsValue(result)){
                    resultmap.put(morse,result);
                }
            }
        }
        return resultmap.size();
    }

    private static void perparenum(String[] numberstr, Map<Integer, String> morsemap) {
        for (int i = 0; i < numberstr.length; i++) {//97-122 is the serial number of letter a-z, so the serial number corresponding to the letter is stored successively from i+97
            morsemap.put(i + 97, numberstr[i]);
        }
    }

Train of thought:

  1. The given Morse password is stored in the HashMap in a circular way, and the key is the serial number corresponding to each letter
  2. The given array is cut through a loop to extract each word
  3. Convert each word to char type to obtain the Morse code stored in the HashMap for the corresponding word one by one
  4. Convert the word to Morse password completely and store it in the independently created resultmap (another HashMap)
  5. When saving, judge whether the value of resultmap contains this value. When not, store it
  6. Returns the length of the result.

 

Posted by bschmitt78 on Wed, 01 Jan 2020 06:27:49 -0800