poj2001字典树

import java.io.BufferedInputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;


public class Main {

        public static void main(String[] args) {

               Scanner cin = new Scanner( new BufferedInputStream(System.in) )  ;
               PrintWriter cout = new PrintWriter(System.out)  ;

               List<String> words = new ArrayList<String>() ;
               while(cin.hasNext()){
                    words.add(cin.next()) ;
               }


               Solve solver = new Solve() ;
               for(String word : words) solver.add(word) ;

               for(String word : words){
                     cout.println(word + " " + solver.get(word)) ;
               }

               cout.flush() ; 
               cout.close() ;

        }




}

class  Tire{
       int  size ;
       Tire[] next = new Tire[26] ;
       Tire(){
            size = 0 ;
            for(int i = 0 ; i < 26 ; i++) next[i] = null ;
       }
}

class Solve{
      Tire root = null ;

      public Solve() {
             root = new Tire() ; 
      } 

      void  add(String word){
            Tire now = root ;
            for(char c : word.toCharArray()){
                   int i = c - 'a' ;
                   if(now.next[i] == null)
                       now.next[i] = new Tire() ;
                   now = now.next[i] ;
                   now.size++ ;
            } 
      }

      String  get(String word){
              StringBuffer sb = new StringBuffer() ;
              Tire now = root ;
              for(char c : word.toCharArray()){
                   int i = c - 'a' ;
                   now = now.next[i] ;
                   sb.append(c) ;
                   if(now.size == 1) return  sb.toString() ;
              } 
              return word ;
      }
}

你可能感兴趣的:(poj2001字典树)