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:
- The given Morse password is stored in the HashMap in a circular way, and the key is the serial number corresponding to each letter
- The given array is cut through a loop to extract each word
- Convert each word to char type to obtain the Morse code stored in the HashMap for the corresponding word one by one
- Convert the word to Morse password completely and store it in the independently created resultmap (another HashMap)
- When saving, judge whether the value of resultmap contains this value. When not, store it
- Returns the length of the result.