93. Restore IP Addresses
Medium

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

Example:

Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]
BONUS:
1.Python中字符串比较大小,是迭代对比的,先比较第一个元素,看谁大就是谁
如果一样再比下一个,所以35比255大,但是1255比255小.如果想比较字符串数值大小
应该转化为int在其前方调用int()函数
2.地址不能以0开头比如00,02所以如果当前的前一个出现了0要直接舍弃
class Solution(object):
    def restoreIpAddresses(self, s):
        """
        :type s: str
        :rtype: List[str]
        """
        def dfs(s,sub,ips,ip):
            if sub==4:
                if s=='':
                    ips.append(ip[1:])
                return

            for i in range(1,4):
                if i<=len(s):
                    if int(s[:i])<=255:
                        dfs(s[i:],sub+1,ips,ip+'.'+s[:i])
                    if s[0]=='0':break
        ips=[]
        dfs(s,0,ips,'')
        return ips




solu=Solution()
s="25525511135"
print(solu.restoreIpAddresses(s))
92. Reverse Linked List II
Medium

Reverse a linked list from position m to n. Do it in one-pass.

Note: 1 ≤ m ≤ n ≤ length of list.

Example:

Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL

import collections
# from collections import Counter
# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def reverseBetween(self,head,m,n):
        if head==None or head.next==None:return head
        # 遍历链表的题目中,虚拟节点是必须的,这样最后移动结束才能由它返回起始值
        dummy=ListNode(0)
        dummy.next=head
        head1=dummy
        # 遍历下标才是这种范围的range,计数就直接写一个迭代次数值
        # 不同题目给的数字不同,有的需要减一才是下标有的可以直接来,这里需要减一
        for i in range(m-1):
            head1=head1.next
        p=head1.next
        for i in range(n-m):
            # 链表题就是费指针,这个的核心转换思路是,把p开始指定后,每次p都会向后移位,head直接跟p后面的,p跟下下一个,head的下下一个是开始时,head后面的值
            tmp=head1.next
            head1.next=p.next
            p.next=p.next.next
            head1.next.next=tmp
        return dummy.next
            



solu=Solution()
head=ListNode(1)
l2=ListNode(2)
l3=ListNode(3)
l4=ListNode(4)
l5=ListNode(5)
# l6=ListNode(2)
head.next=l2
l2.next=l3
l3.next=l4
l4.next=l5
# l5.next=l6
m=2
n=4
ans=solu.reverseBetween(head,m,n)
while True:
    print(ans.val)
    if not ans.next:
        break
    ans=ans.next

 

 

posted on 2019-09-20 10:37  黑暗尽头的超音速炬火  阅读(126)  评论(0编辑  收藏  举报