hankviv / blog_issue

issue
2 stars 0 forks source link

代码段记录 #35

Open hankviv opened 4 years ago

hankviv commented 4 years ago

递归输出树形结构


    public function getChild($lists,$pid = 0)
    {
        $list = [];
        $i = 0;
        foreach ($lists as $key => $item){
            if ($item['parent_id'] == $pid ){
                $list[$i] = $item;
                unset($lists[$key]);
                $list[$i]['child'] = self::getChild($lists,$item['id']);
            }
            $i ++;
        }
        $list =  array_values($list);
        return $list;
    }
hankviv commented 4 years ago

判断是否是字符串和数字:


func isalnum(s byte) bool{
    return s >= 'A' && s <='Z' || s >= 'a' && s <='z' || s >= '0' && s <='9'
}
hankviv commented 4 years ago

字典树

type Trie struct {
    isEnd bool
    next  [26]*Trie
}

/** Initialize your data structure here. */
func Constructor() Trie {
    return Trie{}
}

/** Inserts a word into the trie. */
func (this *Trie) Insert(word string) {
    for _, v := range word {
        if this.next[v-'a'] == nil {
            this.next[v-'a'] = &Trie{}
        }
        this = this.next[v-'a']
    }
    this.isEnd = true
}

/** Returns if the word is in the trie. */
func (this *Trie) Search(word string) bool {
    for _, v := range word {
        if this.next[ v-'a'] == nil {
            return false
        } else {
            this = this.next[v-'a']
        }
    }
    return this.isEnd == true
}

/** Returns if there is any word in the trie that starts with the given prefix. */
func (this *Trie) StartsWith(prefix string) bool {
    for _, v := range prefix {
        if this.next[ v-'a'] == nil {
            return false
        } else {
            this = this.next[v-'a']
        }
    }
    return true
}