两数之和_最长回文子串

1. Two sumGiven an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.You may assume that each input would have exactly one solution, and you may not use the same element twice.You can return
摘要由CSDN通过智能技术生成

1. Two sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

def twoSum(nums, target):
    Dict = {}
    length = len(nums)
    for i in range(length):
        j = target - nums[i]
        if j in Dict:
            return [Dict[j],i]
        Dict[nums[i]] = i
twoSum([2,7,11,15], 9)
[0, 1]

5. Longest Palindromic Substring

Given a string s, return the longest palindromic substring in s

  • Input: s = “babad”
  • Output: “bab”
  • Explanation: “aba” is also a valid answer.
def longestPalindrome(s):
    left = 0
    right = 0
    Matrix = [[False]*len(s) for _ in range(len(s))]
    MaxLength = 0
    for i in range(len(s)-1, -1, -1):
        for j in range(i, len(s)):
            # print(i, j)
            if s[i] == s[j]:
                if j-i <= 1 or Matrix[i+1][j-1] is True:
                    Matrix[i][j] = True
                    
            if Matrix[i][j] is True and j-i+1 > MaxLength:
                left = i
                right = j
                MaxLength = j - i + 1
                
    return s[left:right+1]
longestPalindrome('babad')
'aba'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中求解最文子串的方法有多种,其中包括暴力求解和动态规划等。根据引用[1]和引用中的代码示例,我们可以看到两种暴力求解的方法。这些方法通过列举所有可能的子串并判断是否为文串来找到最文子串。 根据引用中的代码示例,我们可以看到一种使用动态规划的方法。这种方法通过构建一个二维数组来保存子串的文信息,并利用之前计算过的结果来计算新的结果。 根据引用中的代码示例,可以使用以下方法来求解最文子串: 1. 定义一个字符串变量`str`,用于存储最文子串。 2. 定义一个整数变量`longest`,用于存储最文子串度。 3. 使用两层循环,外层循环遍历字符串`s`的每一个字符,内层循环从外层循环的字符开始遍历到字符串`s`的最后一个字符。 4. 在内层循环中,使用`substring`方法获取当前子串。 5. 调用`isPalindromes`方法判断当前子串是否为文串,并且度大于`longest`。 6. 如果是文串且度大于`longest`,则更新`str`和`longest`的值。 7. 返`str`作为最文子串。 根据引用中的代码示例,可以使用以下方法来求解最文子串: 1. 定义一个整数变量`len`,用于存储字符串`s`的度。 2. 如果`len`小于2,直接返`s`作为最文子串。 3. 定义一个整数变量`maxLen`,用于存储最文子串度。 4. 定义一个整数变量`begin`,用于存储最文子串的起始下标。 5. 将字符串`s`转换为字符数组`chars`。 6. 使用两层循环,外层循环遍历字符串中的每一个字符,内层循环从外层循环的字符开始遍历到字符串的最后一个字符。 7. 在内层循环中,判断`chars`数组中从`i`到`j`的子串是否为文串,并且度大于`maxLen`。 8. 如果是文串且度大于`maxLen`,则更新`maxLen`和`begin`的值。 9. 返从`begin`到`begin+maxLen`的子串作为最文子串。 以上是两种求解最文子串的方法,你可以根据实际需求选择其中一种方法进行使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值