Leetcode 211 添加与搜索单词 - 数据结构设计

3 篇文章 0 订阅
<?php
class WordDictionary {
    private $root;
    /**
     * Initialize your data structure here.
     */
    function __construct() {
        $this->root = new Node();
    }
  
    /**
     * Adds a word into the data structure.
     * @param String $word
     * @return NULL
     */
    function addWord($word) {
        $cur = $this->root;
        $len = strlen($word);
        for ($i = 0; $i < $len; $i++) {
            $w = $word[$i];
            if(empty($cur->get($w))) {
                $cur = $cur->set($w);
            } else {
                $cur = $cur->get($w);
            }
        }
        $cur->end();
    }
  
    /**
     * Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
     * @param String $word
     * @return Boolean
     */
    function search($word) {
        return $this->match($this->root, $word, 0);
    }
	
    function match($node, $word, $pos) {
        if ($pos == strlen($word)) {
            return $node->isEnd();
        }
        $ch = $word[$pos];
        if ($ch != '.') {
            if (!$node->get($ch)) {
                return false;
            }
            return $this->match($node->get($ch), $word, $pos+1);
        } else {
            $ar = range('a', 'z');
            foreach ($ar as $ch) {
                if (!$node->get($ch)) {
                    continue;
                }
                if ($this->match($node->get($ch), $word, $pos+1)) {
                    return true;
                }
            }
            return false;
        }
    }
}

class Node {
    private $isEnd = false;
    private $data = array();

    public function isEnd(){
        return $this->isEnd;
    }

    public function end() {
        $this->isEnd = true;
    }

    public function get($key) {
        return isset($this->data[$key]) ? ($this->data[$key]) : null;
    }

    public function set($key) {
        $this->data[$key] = new Node();
        return $this->data[$key];
    }
    function __construct($key = '') {
        if ($key) {
            $this->data[$key] = new Node();
        }
        
    }   
}

/**
 * Your WordDictionary object will be instantiated and called as such:
 * $obj = WordDictionary();
 * $obj->addWord($word);
 * $ret_2 = $obj->search($word);
 */

$obj = new WordDictionary();
$obj->addWord('bad');
$obj->addWord('dad');
$obj->addWord('mad');

$ret_2 = $obj->search('pad');
var_dump($ret_2);

$ret_2 = $obj->search('bad');
var_dump($ret_2);

$ret_2 = $obj->search('.ad');
var_dump($ret_2);

$ret_2 = $obj->search('b..');
var_dump($ret_2);


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值