Method reused JAVA code


  • 0
    W

    For insert, search and startWith, there are a lot of common steps. I just grab those common steps into a private method. This is not in a real project, i didn't encapsulate the field in TrieNode as private in order to make it easy and simple.

    class TrieNode {
        public Map<Character, TrieNode> map=new HashMap<Character, TrieNode>();
        public char c;
        public boolean isLeaf=false;
        public TrieNode() {}
        public TrieNode(char ch){
            c=ch;
        }
    }
    
    public class Trie {
        private TrieNode root;
        public Trie() {
            root = new TrieNode();
        }
        public void insert(String word) {
           operate(root, word, 0);
        }
        public boolean search(String word) {
            return operate(root, word, 1);
        }
        public boolean startsWith(String prefix) {
            return operate(root, prefix, 2);
        }
        private boolean operate(TrieNode node, String word, int oper){
            int len=word.length();
            if(len==0) return true;
            for(int i=0;i<len;i++){
                char c=word.charAt(i);
                if(!node.map.containsKey(c)){
                    if(oper==0) node.map.put(c, new TrieNode(c));
                    else return false;
                }
                node=node.map.get(c);
            }
            if(oper==0) node.isLeaf=true;
            if(oper!=1) return true;
            return node.isLeaf;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.