Algorithm: String Matching Problem

  node.js, question
import java.util.HashMap;
 import java.util.Map;
 public class TestMap {
 public static void main(String[] args) {
 Map<String, String> map = new HashMap<>();
 map.put("1", "1");
 map.put("21", "1");
 map.put("22", "1");
 map.put("23", "1");
 map.put("24", "1");
 map.put("25", "1");
 map.put("26", "1");
 map.put("27", "1");
 map.put("28", "1");
 map.put("29", "1");
 map.put("311", "1");
 map.put("312", "1");
 map.put("313", "1");
 map.put("314", "1");
 map.put("315", "1");
 map.put("316", "1");
 map.put("317", "1");
 map.put("318", "1");
 map.put("319", "1");
 map.put("321", "1");
 map.put("322", "1");
 map.put("323", "1");
 map.put("324", "1");
 map.put("325", "1");
 map.put("326", "1");
 map.put("327", "1");
 map.put("328", "1");
 map.put("329", "1");
 map.put("331", "1");
 map.put("332", "1");
 map.put("333", "1");
 map.put("334", "1");
 map.put("335", "1");
 map.put("336", "1");
 map.put("337", "1");
 map.put("338", "1");
 map.put("339", "1");
 String str = "3333333333";
 for (int i=0;   i<str.length();  I plus)
 String res = map.get(str.substring(0, i));

As in the test class above, the rule of key in map is that the long key does not contain the complete short key from the first character, and then given a string, is there a better algorithm to match the first character to the optimal map value?

Algorithm description: there are millions of keys with different lengths. the rule of key is that the long key does not contain the complete short key from the first character, for example, key(21) does not contain key(1),key(321) does not contain key(3,32), etc. then, given a string of characters, the best match is started from the first character, for example, string of characters 222, and finally match 22 in the given key(21,22, 23), which requires a small amount of calculation and a fast algorithm.