NC78 反转列表& 61 两数之和 & 127最长公共子串

NC 78 反转列表

🎞题目描述

输入一个链表,反转链表后,输出新链表的表头。
难度 ⭐

示例1
输入{1,2,3}
返回值 {3,2,1}

🔱思路

使用迭代法,新建一个新列表,然后每次都像那个列表中插入即可。复杂度O(n).

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # write code here
        new_head = None
        tmp = pHead
        while(tmp):
            if not new_head:
                new_head = ListNode(tmp.val)
            else:
                tmp0 = ListNode(tmp.val)
                tmp0.next = new_head
                new_head = tmp0
            
            tmp = tmp.next
        return new_head

NC61 两数之和

题目描述

给出一个整数数组,请在数组中找出两个加起来等于目标值的数,
你给出的函数twoSum 需要返回这两个数字的下标(index1,index2),需要满足 index1 小于index2.。注意:下标是从1开始的
假设给出的数组中只存在唯一解

例如:
给出的数组为 {20, 70, 110, 150},目标值为90
输出 index1=1, index2=2

难度 ⭐

思路

如果用暴力法,需要两个指针一起遍历,复杂度O(n^2), 那么能不能一次遍历呢?可以使用哈希表来实现。
每次遍历到一个值,就看看target-curr_num是否在哈希表中,如果在,说明已经找到!如果不在,将curr_num和其索引存到哈希表中。

#
# 
# @param numbers int整型一维数组 
# @param target int整型 
# @return int整型一维数组
#
class Solution:
    def twoSum(self , numbers , target ):
        # write code here
        Map = {}
        for i in range(len(numbers)):
            curr = numbers[i]
            if target - curr in Map.keys():
                return [Map[target - curr]+1,i+1]
            ### not fount yet
            Map[curr] = i
            
NC 127. 最长公共子串

难度 ⭐⭐

题目描述

给定两个字符串str1和str2,输出两个字符串的最长公共子串
题目保证str1和str2的最长公共子串存在且唯一。

示例1
输入 “1AB2345CD”,“12345EF”
返回值 “2345”

思路

和之前讲过的“最长公共子序列”不同,这里的子串必须是相邻的,所以转移函数应该为:
LCS(i,j) = LCS(i-1,j-1)+1 if str1[i] == str2[j]
选取最大的那个值和位置即可知道子串。

#
# longest common substring
# @param str1 string字符串 the string
# @param str2 string字符串 the string
# @return string字符串
#
class Solution:
    def LCS(self , str1 , str2 ):
        # write code here
        m = len(str1)
        n = len(str2)
        dp = [[0 for i in range(n+1)] for j in range(m+1)]
        maxlen = 0
        end = 0
        for i in range(1,m+1):
            for j in range(1,n+1):
                if str1[i-1] == str2[j-1]:
                    dp[i][j] = 1 + dp[i-1][j-1]
                if dp[i][j] > maxlen:
                    maxlen = dp[i][j]
                    end = j
        return str2[end-maxlen:end]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值