力扣42题、5题(双指针)

42、接雨水

基本思想:

边走边算

具体实现:

核心思想:位置i的最大水柱高度是min(l_max,r_max)  (左边最大的高度,右边最大的高度)

两个指针left,right分别指向开头结尾

l_max代表height[0...left]的最高柱子

r_max代表height[right...n-1]的最高柱子

只要左边最高的低于右边最高的,就用左边最高的-当前位置的高度

左边最高的高于右边最高的,就去算右边,优先算左边

代码:

class Solution:
    def trap(self, height: List[int]) -> int:
        n = len(height)
        if len(height) <= 1:
            return 0
        left = 0
        right = n-1
        ans = 0
        r_max = height[n-1]
        l_max = height[0]
        while left <= right:
            l_max = max(l_max,height[left])
            r_max = max(r_max,height[right])
            if l_max < r_max:
                ans += l_max-height[left]
                left += 1
            else:
                ans += r_max-height[right]
                right -= 1
        return ans

5、寻找最长回文子串

基本思想:

从中间开始向两边扩散来判断回文串

具体实现:

回文串有两种情况:

1、奇数长度  aba

2、偶数长度 abba

找到以s[i]为中心的回文串,根据找到的回文串更新长度

找到以s[i],s[i+1]为中心的回文串,。。。。。。。。。

代码:

class Solution:
    def expandAroundCenter(self, s, left, right):
        while left >= 0 and right < len(s) and s[left] == s[right]:
            left -= 1
            right += 1
        return left + 1, right - 1

    def longestPalindrome(self, s: str) -> str:
        start, end = 0, 0
        for i in range(len(s)):
            left1, right1 = self.expandAroundCenter(s, i, i)
            left2, right2 = self.expandAroundCenter(s, i, i + 1)
            if right1 - left1 > end - start:
                start, end = left1, right1
            if right2 - left2 > end - start:
                start, end = left2, right2
        return s[start: end + 1]

 

原文地址:https://www.cnblogs.com/zhaojiayu/p/14853748.html