leetcode Day41 剑指专项 27-33

114 阅读1分钟

剑指 Offer II 027. 回文链表

var isPalindrome = function(head) {
    let res=[]
    let node=head
    while(node){
        res.push(node.val)
        node=node.next
    }
    return res.toString()===res.reverse().toString()
};

剑指 Offer II 028. 展平多级双向链表

var flatten = function(head) {
    const dfs = (node) => {
        let cur = node;
        let last = null;
        while (cur) {
            let next = cur.next;
            if (cur.child) {
                const childLast = dfs(cur.child);
                next = cur.next;
                cur.next = cur.child;
                cur.child.prev = cur;
                if (next != null) {
                    childLast.next = next;
                    next.prev = childLast;
                }
                cur.child = null;
                last = childLast;
            } else {
                last = cur;
            }
            cur = next;
        }
        return last;
    }
    dfs(head);
    return head;
};

剑指 Offer II 029. 排序的循环链表

var insert = function(head, insertVal) {
    const newNode=new Node(insertVal)
    if(head===null){
        head=newNode
        head.next=head
    }
    else if(head.next===null){
        head.next=newNode
        newNode.next=head
    }else{
        let cur=head
        let next=head.next
        let maxNode=head
        while(!(cur.val<=newNode.val && next.val>=newNode.val)&& next!==head){
            cur=next
            next=next.next
            maxNode=cur.val>=maxNode.val?cur:maxNode
        }
        if(cur.val<=newNode.val && next.val>=newNode.val){
            cur.next=newNode
            newNode.next=next
        }else{
            newNode.next=maxNode.next
            maxNode.next=newNode
        }
    }
    return head
};

剑指 Offer II 032. 有效的变位词

var isAnagram = function(s, t) {
    return s.split('').sort().join('')===t.split('').sort().join('') && s!==t
};

剑指 Offer II 033. 变位词组

var groupAnagrams = function(strs) {
    let map=new Map()
    for(let i of strs){
        let key=i.split('').sort().join('')
        if(map.has(key)){
            map.set(key,[...map.get(key),i])
        }else{
            map.set(key,[i])
        }
    }
    return Array.from(map.values())
};