Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package tries;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.Statement;
- import java.util.ArrayList;
- import java.util.List;
- public class TrieDB {
- public static void main(String[] args) {
- String url = "jdbc:mysql://localhost:3306/sakila";
- String user = "root";
- String password = "secret";
- final List<String> setOfStrings = new ArrayList<>();
- try {
- Class.forName("com.mysql.jdbc.Driver");
- Connection conn = DriverManager.getConnection(url, user, password);
- String sql = "select first_name from actor ";
- Statement stmt = conn.createStatement();
- ResultSet rs = stmt.executeQuery(sql);
- while(rs.next())
- {
- String firstName = rs.getString("first_name");
- setOfStrings.add(firstName);}
- }catch (Exception ex) {
- ex.printStackTrace();
- }
- System.out.println(setOfStrings);
- final Trie trie = new Trie();
- // setOfStrings.forEach(trie::insert);
- for(String s : setOfStrings) {
- System.out.println(trie.query(s));
- }
- }
- }
- class Trie {
- final TrieNode root;
- public Trie() {
- this.root = new TrieNode();
- }
- public int query(final String s) {
- TrieNode current = root;
- for (int i = 0; i < s.length(); i++) {
- if(current==null || current.next(s.charAt(i))==null) {
- return 0;
- }
- else
- current=current.next(s.charAt(i));
- }
- return current.terminating;
- }
- public void insert(final String s) {
- TrieNode current = root;
- char c;
- for (int i = 0; i < s.length(); i++) {
- if(s.charAt(i)<=90) {
- if (current.trieNodes[s.charAt(i) - 'A'] == null) {
- current.trieNodes[s.charAt(i) - 'A'] = new TrieNode();
- }
- }
- else {
- if (current.trieNodes[s.charAt(i) - 'a'] == null) {
- current.trieNodes[s.charAt(i) - 'a'] = new TrieNode();
- }
- }
- current = current.next(s.charAt(i));
- }
- current.terminating++;
- }
- }
- class TrieNode {
- int terminating;
- final TrieNode[] trieNodes = new TrieNode[58];
- public TrieNode next(final char c) {
- return trieNodes[c - 'a'];
- }
- }
Add Comment
Please, Sign In to add comment