2017-09-25 46 views
-4

問題 Autocomptete無法通過測試情況下,自動完成

道格是和驚訝地看到autocomptete功能autocomptete如何工作,在數據庫中搜索所有可使用的字符形成可能的話由用戶(作爲輸入)

對於離提供。如果在搜索欄中用戶類型「順式」,那麼建議將是

•思科

•CIST

•CISSP

•CISM

•CISA 他想在他的搜索引擎應用相同的功能。在他的原型中,他把一個字符串作爲一個包含他可以搜索的所有單詞的域。 作爲他的設計師,你必須告訴他,如果在輸入字段中輸入了什麼內容,將爲他提供多少個autocomptete選項。

這是我對以下問題的代碼。

import java.util.ArrayList; 
import java.util.List; 


public class Test { 

public static void main(String[] args) { 


    String input1 = "Hello world with warm welcome from Mr.kajezevu"; 
    String input2 = "w"; 
    //output should be any word starting with w i.e {world,warm,welcome} 




    List <String> l = new ArrayList <String>(); 



    String[] str = input1.split("\\s+");//splits a given string at spaces 
    for (int i = 0; i < str.length; i++) { 
     if (str[i].length() >= input2.length()) { // checks if the length of input2 is not greater than the str[i] selected 
      if (input2.equals(str[i].substring(0, input2.length()))) { //comparing the two string if they are equal 
       l.add(str[i]); 
      } 

     } 
    } 

    String[] result = l.toArray(new String[l.size()]); 

    for (int i = 0; i < result.length; i++) { 
     System.out.println(result[i]); 
    } 
} 


} 

但我的解決方案是隻通過一個測試案例,也沒有它的複雜情況。 我無法弄清楚它有什麼問題。

+3

如果您的代碼沒有像預期的那樣運行,那麼現在是時候進行一些調試了。 –

+0

家庭作業再次發生! –

回答

0

看起來你錯過了邊界條件。 以下是代碼。

public static String[] autoComplete(String input1, String input2){ 
    List<String> listOfPredictions = new ArrayList<String>(); 
    String[] emptyArr = new String[0]; 
    if(isEmpty(input1) || isEmpty(input2)){ 
     return emptyArr; 
    } 
    input1 = input1.trim(); 
    input2 = input2.trim(); 
    String tokenizer = " " + input2; 
    int fromIdx = 1; 
    if(input1.startsWith(input2)){ 
     fromIdx = input1.indexOf(" "); 
     listOfPredictions.add(input1.substring(0, fromIdx)); 
    } 

    while(fromIdx > 0){ 
     fromIdx = input1.indexOf(tokenizer, fromIdx) + 1; 
     if(fromIdx > 0){ 
      listOfPredictions.add(input1.substring(fromIdx, input1.indexOf(" ", fromIdx))); 
     } 
    } 

    return listOfPredictions.toArray(emptyArr); 
} 

private static boolean isEmpty(String str){ 
    return str == null || str.trim().length() == 0; 
} 
相關問題