电话号码的字母组合+ 删除链表的倒数第N个节点

17. 电话号码的字母组合

难度中等620收藏分享切换为英文关注反馈

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

示例:

输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
#循环,递归将已有字母组合和新字母组合
def letterCombinations(digits):
    phone = {'2': ['a', 'b', 'c'],
             '3': ['d', 'e', 'f'],
             '4': ['g', 'h', 'i'],
             '5': ['j', 'k', 'l'],
             '6': ['m', 'n', 'o'],
             '7': ['p', 'q', 'r', 's'],
             '8': ['t', 'u', 'v'],
             '9': ['w', 'x', 'y', 'z']}
    
    def combine(combination,next_digits):
        if len(next_digits)==0:
            output.append(combination)
        else:
            for char in phone[next_digits[0]]:
                combine(combination+char,next_digits[1:])
    output = []
    if digits:
        combine("",digits)
    return output

19. 删除链表的倒数第N个节点

难度中等733收藏分享切换为英文关注反馈

给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。

示例:

给定一个链表: 1->2->3->4->5, 和 n = 2.

当删除了倒数第二个节点后,链表变为 1->2->3->5.
class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        if not head:
            return None
        node = ListNode(-1)
        node.next = head
        #创建快慢指针
        frist = node
        second = node
        while n+1>0:#向前移动 n+1 步
            frist = frist.next
            n -= 1
        while frist:
            frist = frist.next
            second = second.next
        second.next = second.next.next
        return node.next
posted @ 2020-03-20 14:55  鱼与鱼  阅读(158)  评论(0编辑  收藏  举报