-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree.php
71 lines (52 loc) · 1.52 KB
/
tree.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php
class tree{
public $treeRoot = array(
'name'=>'',
'count'=>0,
'child'=>array()
);
public function insertNode($word){
$charArray = str_split($word);
$currentNode = & $this->treeRoot;
for($i=0, $len=count($charArray); $i<$len; $i++){
$currentChar = $charArray[$i];
if(!isset($currentNode['child'][$currentChar])){
$currentNode['child'][$currentChar] = array(
'name'=>$currentChar,
'count'=>0,
'child'=>array()
);
}
$currentNode = & $currentNode['child'][$currentChar];
if($i===$len-1){
$currentNode['count'] += 1;
}
}
}
public function aggregate($node, $prevString, & $result){
$currentString = $prevString.$node['name'];
if($node['count'] != 0){
$result[$currentString] = $node['count'];
}
foreach($node['child'] as $key=>$childNode){
$this->aggregate($childNode, $currentString, $result);
}
return $result;
}
public function dealContent($filePath){
$content = file_get_contents($filePath);
$content = preg_replace("/[^a-zA-Z']+/", ' ', $content);
$content = preg_replace("/\s+$/", '', $content);
return $content;
}
}
$tree = new tree();
$contentArray = explode(' ', $tree->dealContent('./sample.txt'));
foreach($contentArray as $word){
$tree->insertNode($word);
}
$result = array();
$tree->aggregate($tree->treeRoot, '', $result);
arsort($result);
var_dump($result);
?>