<?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);
Leetcode 211 添加与搜索单词 - 数据结构设计
最新推荐文章于 2020-09-14 14:41:18 发布