LeetCode 2.Add Two Numbers 3.Longest Substring Without Repeating Characters 解析

2.Add Two Numbers 

原题:

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

翻译:

给你两个非空链表,表示两个非负整数。数字以相反的顺序存储,每个节点包含一个数字。添加这两个数字并将其作为链接列表返回。

您可以假定这两个数字不包含任何前导零,除了数字0本身。

输入:(2→4→3)+(5→6→4)
 输出: 7→0→8
 说明: 342 + 465 = 807。













解析:把两个链表当成是相同长度的,短的那个想象成后面都是0;如果进位的话,在初始化下一个节点的时候将其赋值为1即可,所以在计算当前节点的值时要加上自己本来的值

class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

    # Define this to check if it works well
    def myPrint(self):
        print(self.val)
        if self.next:
            self.next.myPrint()


class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        result = ListNode(0);
        cur = result;
        while l1 or l2:
            cur.val += self.addTwoNodes(l1, l2)
            if cur.val >= 10:
                cur.val -= 10
                cur.next = ListNode(1)
            else:
                # Check if there is need to make the next node
                if l1 and l1.next or l2 and l2.next:
                    cur.next = ListNode(0)
            cur = cur.next
            if l1:
                l1 = l1.next
            if l2:
                l2 = l2.next
        return result

    def addTwoNodes(self, n1, n2):
        if not n1 and not n2:
            # This cannot happen, ignore it
            None
        if not n1:
            return n2.val
        if not n2:
            return n1.val
        return n1.val + n2.val


if __name_
class NodeList(object):
    """docstring for NodeList"""
    def __init__(self, x):
        self.val=x
        self.next=None
    def Creatlist(n):  
        if n<=0:  
            return False  
        if n==1:  
            return ListNode(1)    # 只有一个节点  
        else:  
            root=ListNode(1)  
            tmp=root  
            for i in range(2,n+1):       #  一个一个的增加节点  
                tmp.next=ListNode(i)  
                tmp=tmp.next  
        return root            # 返回根节点


class sulotion:
    """输入两个倒序链表。相加后倒叙输出"""
    def addTwoNums(self,l1,l2):
        '''两个链表相加'''
        result=NodeList(0)
        cur=result
        while l1 or l2:
            cur.val+=self.addTwoNode(l1,l2)
            if cur.val>=10:
                cur.val-=10
                cur.next=NodeList(1)
            else:
                if l1 and l1.next or l2 and l2.next:
                    cur.next=NodeList(0)
            cur=cur.next
            if l1:
                l1=l1.next
            if l2:
                l2=l2.next
        return result
    def addTwoNode(self,n1,n2):
        '''两个节点相加'''
        if not n1 and not n2:
            return None
        if not n1:
            return n2.val
        if not n2:
            return n1.val
        return n1.val+n2.val
    def printList(self, head):
        '''打印链表'''
        p=head  
        while p!=None:  
            print(p.val)  
            p=p.next  
    def listlen(self,head):       
    '''链表长度  '''
        c=0  
        p=head  
        while p!=None:  
            c=c+1  
            p=p.next  
        return c  
    def insert(self,head,n):         # 在n的前面插入元素  
        if n<1 or n>listlen(head):  
            return  
      
        p=head  
        for i in range(1,n-1):  # 循环四次到达 5  (只能一个一个节点的移动 range不包含n-1)
            p=p.next  
        a=raw_input("Enter a value:")  
        t=ListNode(value=a) 
        t.next=p.next   
        p.next=t   
        return head       
  
    def dellist(self,head,n):  # 删除链表  
        if n<1 or n>listlen(head):  
            return head  
        elif n is 1:  
            head=head.next   # 删除头  
        else:  
            p=head  
            for i in range(1,n-1):    
                p=p.next     # 循环到达 2次   
            q=p.next  
            p.next=q.next    # 把5放在3的后面  
        return head

    
if __name__=="__main__":
    list=NodeList(9)
    list.next=NodeList(8)
    sulotion().printListFromTailToHead(list)
    p=sulotion().addTwoNums(list,NodeList(1))
    sulotion().printListFromTailToHead(p)
    # print(sulotion().addTwoNums(list, NodeList(1))) 
    

_ == "__main__": list = ListNode(9) list.next = ListNode(8) print(Solution().addTwoNumbers(list, ListNode(1)).myPrint())

一些链表的操作






3.Longest Substring Without Repeating Characters

原题

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring"pwke" is a subsequence and not a substring.

翻译:

给定一个字符串,找到最长的子字符串的长度,不重复字符。

例子:

给定"abcabcbb"的答案是"abc",长度是3。

给定"bbbbb"的答案是"b",长度为1。

给定"pwwkew"的答案是"wke",长度为3.请注意,答案必须是一个子字符串"pwke"是一个序列,而不是一个子字符串。








解析:将每个字母放到依次放到map,如果不存在就加入,存在就退出。最后返回map里字母个数

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        max=0
        for i in range(len(s)):
            hash_map={}
            count=0
            for j in range(i,len(s)):
                #判断是否在map的键中
                if s[j] not in hash_map.keys():
                    #s[j]为键,count为值
                    hash_map[s[j]]=count
                    count+=1
                    if count>max:
                        max=count
                else:
                    break 
        return max               

if __name__=="__main__":
    s=Solution().lengthOfLongestSubstring("pwwkew")
    print(s)

思路二: 将没有重复字符的子串称为目标字符串。遍历字符串的所有字符,记录下每个字符最近出现的下标位置,如果该下标比目标字符串的起始下标大,说明目标字符串中已经有该字符了,刷新目标字符串的起始坐标。找出所有目标串的最大长度就是题目要求的答案。
class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s:
            return 0
        if len(s) <= 1:
            return len(s)
        locations = [-1 for i in range(256)]
        index = -1
        m = 0
        for i, v in enumerate(s):
            if (locations[ord(v)] > index):
                index = locations[ord(v)]
            m = max(m, i - index)
            locations[ord(v)] = i
        return m

if __name__ == "__main__":
    assert Solution().lengthOfLongestSubstring("abcea") == 4

1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值