LeetCode day13

views 1160 words

Diffculty: Medium

2. Add Two Numbers

Topic: Linked list, Math

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.

Approach1

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

def addTwoNumbers(l1: ListNode, l2: ListNode) -> ListNode:
    carry=0
    res = ListNode(0)
    restemp = res
    while l1 or l2:
        x = l1.val if l1 else 0
        y = l2.val if l2 else 0
        sum = x + y + carry
        carry = sum // 10
        restemp.next = ListNode(sum % 10)
        # print(restemp,'11111')  # ListNode{val: 0, next: ListNode{val: 7, next: None}}
        restemp = restemp.next  # ListNode{val: 7, next: None}
        # print(restemp,'22222')
        if l1:
            l1 = l1.next
        if l2:
            l2 = l2.next
        # print(res.next,'======')
    if carry != 0:
        restemp.next = ListNode(1)
    return res.next

3. Longest Substring Without Repeating Characters

Topic: Hash Table, Two pointer, String, Sliding Windows

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

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3. 

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: "pwwkew"
Output: 3
Explanation: 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.

Approach1

my, but fking slow…..

def lengthOfLongestSubstring(s: str) -> int:
    if not s: return 0
    tmpmax = 1
    for i in range(len(s)):
        tmp = [s[i]]
        for j in range(i+1,len(s)):
            if s[j] not in tmp:
                tmp.append(s[j])
            else:
                break
        tmpmax = max(len(tmp),tmpmax)
    return tmpmax

Approach2

bd11f4ab67cedf43e763056120a3407b34458136607d989d2566e87d18199ced-3.longestSubstringWithoutRepeatingCharacters

def lengthOfLongestSubstring(s: str) -> int:
    res = 0
    r = 0
    tmp = set()
    for i in range(len(s)):
        if i != 0:
            tmp.remove(s[i-1])
        while r < len(s) and s[r] not in tmp:
            tmp.add(s[r])
            r += 1
        res = max(len(tmp),res)
    return res

时间复杂度:O(N),其中N为字符串长度 空间复杂度:O(N),其中N为字符串长度

5. Longest Palindromic Substring

Topic: String, DP

Given a string s, find the longest palindromic substring(最长回文子字符串) in s. You may assume that the maximum length of s is 1000.

Example 1:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example 2:

Input: "cbbd"
Output: "bb"

Approach1

  • Brute Force, 根据回文子串的定义,枚举所有长度大于等于 2 的子串,依次判断它们是否是回文
  • 在具体实现时,可以只针对大于“当前得到的最长回文子串长度”的子串进行“回文验证”;
  • 在记录最长回文子串的时候,可以只记录“当前子串的起始位置”和“子串长度”,不必做截取。这一步我们放在后面的方法中实现

    def longestPalindrome(s: str) -> str:
    # 特判
    size = len(s)
    if size < 2:
        return s
    
    max_len = 1
    res = s[0]
    
    # 枚举所有长度大于等于 2 的子串
    for i in range(size - 1):
        for j in range(i + 1, size):
            if j - i + 1 > max_len and self.__valid(s, i, j):
                max_len = j - i + 1
                res = s[i:j + 1]
    return res
    
    def __valid(s, left, right):
    # 验证子串 s[left, right] 是否为回文串
    while left < right:
        if s[left] != s[right]:
            return False
        left += 1
        right -= 1
    return True

Approach2

回文串:

  1. 如果一个字符串的头尾两个字符都不相等,那么这个字符串一定不是回文串;
  2. 如果一个字符串的头尾两个字符相等,才有必要继续判断下去

    1. 如果里面的子串是回文,整体就是回文串;
    2. 如果里面的子串不是回文串,整体就不是回文串

      def longestPalindrome(s: str) -> str:
      size = len(s)
      if size < 2:
      return s
      
      dp = [[False for _ in range(size)] for _ in range(size)]
      
      max_len = 1
      start = 0
      
      for i in range(size):
      dp[i][i] = True
      
      for j in range(1, size):
      for i in range(0, j):
          if s[i] == s[j]:
              if j - i < 3:
                  dp[i][j] = True
              else:
                  dp[i][j] = dp[i + 1][j - 1]
          else:
              dp[i][j] = False
      
          if dp[i][j]:
              cur_len = j - i + 1
              if cur_len > max_len:
                  max_len = cur_len
                  start = i
      return s[start:start + max_len]

时间复杂度:O(N^{2}) 空间复杂度:O(N^{2}),二维 dp 问题,一个状态得用二维有序数对表示,因此空间复杂度是 O(N^{2}).

8. String to Integer (atoi)

Topic: Math, String

Implement atoi which converts a string to an integer.

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned.

Note:

  • Only the space character ‘ ’ is considered as whitespace character.
  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: $[−2^{31},  2^{31} − 1]$. If the numerical value is out of the range of representable values, INT_MAX ($2^{31} − 1$) or INT_MIN ($−2^{31}$) is returned.

Example 1:

Input: "42"
Output: 42

Example 2:

Input: "   -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.
             Then take as many numerical digits as possible, which gets 42.

Example 3:

Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.

Example 4:

Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical 
             digit or a +/- sign. Therefore no valid conversion could be performed.

Example 5:

Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
             Thefore INT_MIN (−231) is returned.

Approach1

my

def myAtoi(s: str) -> int:
    flag, ans = None, []
    for c in s:
        if c == ' ' and not ans and not flag:
            continue
        elif c in '+-' and not flag and not ans:
            flag = (1 if c=='+' else -1)
        elif c in '0123456789':
            ans.append(c)
        else:
            break
    if not ans:
        return 0
    ans = (flag if flag else 1)*int(''.join(ans))
    return ans if -2**31<=ans<=2**31-1 else (2**31-1 if ans>0 else -2**31)

Approach2

def myAtoi(str: str) -> int:
    numdic = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
    i = 0
    # 跳过前面的空白
    while i < len(str) and str[i] == ' ':
        i += 1
    # 判断异常转换情况
    if i >= len(str) or (str[i] not in numdic and str[i] not in ('+','-')):
        return 0
    # 判断正负性
    sign = 1
    if str[i] == '-':
        sign = -1
        i += 1
    elif str[i] == '+':
        i += 1
    # 提取数
    num = 0
    boundry = (1<<31)-1 if sign > 0 else 1<<31
    # 注意先判断索引,以防越界
    while i < len(str) and str[i] in numdic:
        num = num *10 + numdic[str[i]]
        i += 1
        if num > boundry:
            return sign * boundry
    return sign * num

Approach3

re

^:匹配字符串开头
[\+\-]:代表一个+字符或-字符
?:前面一个字符可有可无
\d:一个数字
+:前面一个字符的一个或多个
\D:一个非数字字符
*:前面一个字符的0个或多个
def myAtoi(s: str) -> int:
    # res = re.findall('^[\+\-]?\d+', s.lstrip())
    # print(res,type(res)) # ['42'], list
    # print(*res,type(*res)) # '42' str
    return max(min(int(*re.findall('^[\+\-]?\d+', s.lstrip())), 2**31 - 1), -2**31)