나는 현재 hackerrank Tries - Contacts시도 횟수 - 연락처 - Hackerrank
에이 문제를 해결하기 위해 노력하고 그리고 내 알고리즘은 하나의 테스트 케이스 실패합니다. 테스트 케이스 # 1. 이 테스트 케이스를 통과하기 위해 내가 바꿀 필요가있는 것을 통찰력을 공유 할 수 있습니까? 그 자식 노드의 해시 맵을 포함하는 TrieNode 클래스를 사용하고 있습니다. 또한 각 노드의 크기를 저장하여 얼마나 많은 단어가 들어 있는지를 결정합니다. 다음과 같이
add s
add ss
add sss
add ssss
add sssss
find s
find ss
find sss
find ssss
find sssss
find ssssss
코드는 다음과 같습니다 : 다음과 같이
테스트 케이스 # 1은
마지막 하나를 제외한 모든 노드의 개수가 증가하여 트리는에 단어를 추가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