php 求解最长公共前缀(字典树)

leetcode 题解

<?php
class Solution
{

    /**
     * @param String[] $strs
     * @return String
     */
    public function longestCommonPrefix($strs)
    {
        if (empty($strs)) {
            return "";
        }
        foreach ($strs as  $value) {
            if(empty($value)){
                return "";
            }
        }
        if(!isset($strs[1])){
            return $strs[0];
        }
        $head = new Node();
        foreach ($strs as  $str) {
            // 加入字典树
            $this->addString($head, $str);
        }
        
        // 获取公共最长前缀
        $a = $this->getMaxComPrex($head);
        return $a;
    }

        /* 获取所有字符串--递归 */
        public function getMaxComPrex($node, $str_array = array(), $str = '')
        {
   
            if (count($node->childNode)>1) {
                return $str;
            } else {
                foreach ($node->childNode as $k => $v) {
                    if ($v->is_end == true) {
                        return  $str. $v->value;
                    }
                    $str = $this->getMaxComPrex($v, $str_array, $str . $v->value);
                }
                return $str;
            }
        }
/* 添加字符串 */ public function addString(&$head, $str) { $node = null; for ($i=0; $i < strlen($str); $i++) { if ($str[$i] != '') { $is_end = $i != (strlen($str) - 1) ? false : true; if ($i == 0) { $node = $head->addChildNode($str[$i], $is_end); } else { $node = $node->addChildNode($str[$i], $is_end); } } } } } class Node { public $value; public $is_end=false; public $childNode; public function addChildNode($value, $is_end=false) { $node = $this->searchChildNode($value, $is_end); if (empty($node)) { // 不存在节点,添加为子节点 $node = new Node(); $node->value = $value; $this->childNode[] = $node; } if($node->is_end==false){ $node->is_end = $is_end; } return $node; } /* 查询子节点 */ public function searchChildNode($value) { foreach ($this->childNode as $k => $v) { if ($v->value == $value) { // 存在节点,返回该节点 return $this->childNode[$k]; } } } } $k = ["aaa","aa","aaa"]; //$k = ["ab","a"]; $s = new Solution(); $s->longestCommonPrefix($k);

 

posted @ 2022-06-11 09:19  阿飞afei  阅读(52)  评论(0编辑  收藏  举报