簡體   English   中英

如何在Android中遍歷非常大的字符串數組?

[英]How to iterate through very large string arrays in Android?

我是Android編程的新手。 我正在嘗試創建一個基本的應用程序,該應用程序將使用輸入的字母“機架”向用戶顯示可能的“拼字游戲”單詞(基於https://openhatch.org/wiki上的Python項目) / Scrabble_challenge )。

“拼字詞典”文本文件的每一行都包含一個單獨的單詞,該單詞被讀入字符串數組(單詞)。 那部分工作正常

接下來,我要遍歷單詞數組,對於每個單詞,我都要遍歷單詞中的字符,測試每個字符是否包含在用戶的字母“機架”中。 如果是,則將該字母從“機架”中刪除。 然后,如果有條件語句,則將當前單詞添加到有效單詞的ArrayList中。

但是,單詞數組包含大約270,000個單詞。 我認為這就是我的問題所在。 我試圖在一個單獨的線程中運行此過程,但是該應用程序遍歷單詞數組的速度非常慢, 最終由於內存不足錯誤而崩潰

這是我的單詞分析代碼:

public void wordFinder(){
    Runnable runnable = new Runnable(){
        public void run(){
            // Loop through each word in wordList
            for(int i = 0; i < wordList.length; i++){
                // Number of letters that are removed from the user's rack
                removed = 0;
                // Create a temporary rack of letters that can be modified within
                // the loop
                temp_rack = input_rack;
                // Loop through each letter of the current word
                for(int j = 0; j < wordList[i].length(); j++){
                    // Save the letter at the position j of the ith word
                    c = wordList[i].charAt(j);
                    // Does the user's rack contain this letter?
                    if(temp_rack.contains(Character.toString(c))){
                        // Replace the first occurrence of the letter in the user's rack
                        temp_rack.replaceFirst(Character.toString(c), "");
                        // Increment the counter for number of removed letters
                        removed++;
                    }
                }
                // If the number of removed letters matches the length of the ith word,
                // the word can be created from the user's rack, and so it is valid.
                // Append it to the temporary valid word list.
                if(removed == wordList[i].length()){
                     temp_valid_word_list.add(wordList[i]);
                }
            }
            // The valid word list is an array representation of the ArrayList
             valid_word_list = temp_valid_word_list.toArray(new String[0]);
        }
    };
    Thread mythread = new Thread(runnable);
    mythread.start();
}

附加信息:

  • wordList是一個標准的字符串數組(約有270,000個元素)
  • input_rack是從EditText框中捕獲為字符串的用戶輸入
  • onClick偵聽器調用wordFinder

沒有理由將此類數據存儲在數組中。 嘗試使用SQLite及其構建搜索功能,這是更合適的方法。

我會使用特里數據結構。 它為您提供O(m)查找時間,其中m是單詞的長度(本質上是一個字符串比較),並且非常有效地使用了內存。 為了您的目的,它是最有效的數據結構。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM