Java |如何按字典搜索模式

问题描述

我的代码是按字典匹配的模式(每个字母都有多个索引),我的代码应首先进入字典,检查pattern是否等于索引dic,然后返回结果

我的问题:

1- dic返回small和captel和number,但是我只需要small和space,我的文本文件仅包含小词和空白。

2-。需要时间(例如:在文本文件+6000-> 1,0017 ..中搜索patt“ and”时) 我认为这很慢,不确定!

 public static void search(JTextArea jTextArea2,String pat) 
    { 
    
         String text = jTextArea2.toString();  
            char[] textArray = text.tochararray();

            //a dictionary that will hold the letter as the key and a list of it's positions as the value.
            HashMap<Character,ArrayList<Integer>> dictionary = new HashMap<Character,ArrayList<Integer>>();

            //loop through the text to check each letter
            for (int i = 0; i < textArray.length; i++) {            

                //if you've already checked this letter,skip to the next one
                if(dictionary.containsKey(textArray[i])) {
                    continue;
                }       

                //add the letter's position to its position list
                ArrayList<Integer> positionList = new ArrayList<>();
                positionList.add(i);

              //compare the remaining letters in the text to the current letter
                for (int j = i+1; j < textArray.length; j++) {

                        //if a letter matches,add it's position to the list
                        if(textArray[i] == textArray[j]) {
                        positionList.add(j);
                    }   
                }               

                //add the letter and its list of positions to the dictionary
              
                dictionary.put(textArray[i],positionList);
            }
           
            //format the response
            for(char key : dictionary.keySet()) {
                ArrayList<Integer> positions = new ArrayList<>();
                positions = dictionary.get(key);
                System.out.println(key + " has an occurance of " + positions.size() + " on positions: " + positions); 
                boolean flag = dictionary.containsKey(key);
                if (flag == true) {
                     System.out.println("result : \t"+ dictionary.containsKey(positions) );
                }
                }
            
            

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)