目前我正在試圖解決的hackerrank Tries - Contacts嘗試次數 - 聯繫方式 - Hackerrank
這個挑戰,只有一個測試用例我的算法失敗。測試用例#1。任何人都可以分享我需要改變的內容,以便通過這個測試用例。我正在使用包含其子節點的散列表的TrieNode類。我還存儲每個節點的大小以確定它包含的單詞的大小。
測試案例#1如下:
add s
add ss
add sss
add ssss
add sssss
find s
find ss
find sss
find ssss
find sssss
find ssssss
的代碼如下:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
TrieNode root;
class TrieNode{
Map<Character, TrieNode> children = new HashMap<Character, TrieNode>();
int size=0;
}
public Solution(){
root = new TrieNode();
}
public void addWord(String word){
TrieNode current = root;
for(int i=0;i<word.length();i++){
char c = word.charAt(i);
if(!current.children.containsKey(c)){
//create a new node
TrieNode temp = new TrieNode();
//add the word to the current node's children
current.children.put(c, temp);
current.size++;
current = temp;
}
else{
current.size++;
current = current.children.get(c);
}
}
}
public void prefixSearch(String letters){
TrieNode current = root;
boolean sequenceExists = true;
for(int i=0; i<letters.length();i++){
char c = letters.charAt(i);
if(current.children.containsKey(c)){
if(i == letters.length()-1){
System.out.println(current.size);
break;
}
else{
current = current.children.get(c);
}
}
else{
System.out.println(0);
break;
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
Solution sol = new Solution();
for(int a0 = 0; a0 < n; a0++){
String op = in.next();
String contact = in.next();
if(op.equals("add")){
if(contact.length() >=1 && contact.length() <=21)
sol.addWord(contact);
}
else if(op.equals("find")){
if(contact.length() >=1 && contact.length() <=21)
sol.prefixSearch(contact);
}
else{
//do nothing
}
}
}
}
什麼是測試用例#1? – EJoshuaS
我會將它添加到他的問題 – Spindoctor
有一秒鐘,我以爲你被一個蟒蛇佔有。 – Kayaman