Add and Search Word - Data structure design


  • 0
    S

    class WordDictionary {

    /** Initialize your data structure here. */
    ArrayList<String> s;
    
    public WordDictionary() {
        
       s=new ArrayList<String>();
        
    }
    
    /** Adds a word into the data structure. */
    public void addWord(String word) {
        
        this.s.add(word);
        
    }
    
    /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
    public boolean search(String word) {
        boolean r= false;
            int c=0;
     
        if(word.contains("."))
        {
            int k=0;
    

    //to check if word has all "."
    while(k<word.length())
    if(word.charAt(k)=='.')
    {
    k++;
    }
    if(k==word.length())
    {
    return true;
    }

           // System.out.println(word+"here with dots");
            for(String ele:this.s)
            {
                if(ele.length()==word.length())
                {
                    for(int i=0;i<ele.length();i++)
                    {
                        if(word.charAt(i)!='.' && word.charAt(i)==ele.charAt(i))
                        {
                            c++;
                        }
                    }
                    
                }
            }
        
            if(c>0){r=true;}
        }
        
        
        else if(this.s.contains(word))
            r=true;
        
    
        
        return r;
    }
    

    }

    /**

    • Your WordDictionary object will be instantiated and called as such:
    • WordDictionary obj = new WordDictionary();
    • obj.addWord(word);
    • boolean param_2 = obj.search(word);
      */

Log in to reply
 

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