-3
\$\begingroup\$

I have made a search function that seems to work for passing the tester. I am just unsure if it will always be without errors. Can someone tell me if they see any flaws in the logic, and if so, where to look to improve?

Search function

//looks up the word in the  object. If it is in the object,true is returned. 
//You can assume that the word will be all lower case.
bool search(const string& word) const {

    if (!root_) {
            return false;
    }

    Node* curr = root_;

    for (int i = 0; i < word.length(); i++)
    {
            int idx = curr->getIndex(word[i]);

            if (idx < 0 || idx >= 26){
                    return false;
            }
            if (!curr->children_[idx]) {
                    return false;
            }
            curr = curr->children_[idx];

    }
    return curr->isTerminal_ == true;
}

Trie node

struct Node {
            bool isTerminal_;
            char ch_;
            Node* children_[26];
            Node(char c = '\0') {
                    isTerminal_ = false;
                    ch_ = c;
                    for (int i = 0; i < 26; i++) {
                            children_[i] = nullptr;
                    }
            }
            //given lower case alphabetic charachters ch, returns 
            //the associated index 'a' --> 0, 'b' --> 1...'z' --> 25
            int getIndex(char ch) {
                    return ch - 'a';
            }
    };
    Node* root_;
\$\endgroup\$
  • \$\begingroup\$ What's the "tester"? \$\endgroup\$ – Riker Apr 15 '17 at 1:47
1
\$\begingroup\$

Design.

Looks like perfectly good C but its not C++.

You should create a Tree class that wraps the node and acts as the interface to all your operations and handles all the resource management. None of these essential parts are currently done.

I would expect an interface like:

class Tree
{
    public:
        void addWord(std::string const& word);
        bool isWork(std::string const& word);
};

The code that you provided looks like it would work but this is far from a complete object and thus not really worth reviewing further.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.