2019-11-24

Python 2nd week

class Solution(object):
  def restoreIpAddresses(self, s):
    """
    :type s: str
    :rtype: List[str]
    """
    ans = []
    n = len(s)

    def isValid(num):
      if len(num) == 1:
        return True
      if len(num) > 1 and num[0] != "0" and int(num) <= 255:
        return True
      return False

    for i in range(0, min(3, n - 3)):
      a = s[:i + 1]
      if not isValid(a):
        break
      for j in range(i + 1, min(i + 4, n - 2)):
        b = s[i + 1:j + 1]
        if not isValid(b):
          break
        for k in range(j + 1, min(j + 4, n - 1)):
          c = s[j + 1:k + 1]
          d = s[k + 1:]
          if not isValid(c):
            break
          if not isValid(d):
            continue
          ans.append("{}.{}.{}.{}".format(a, b, c, d))
    return ans
class Solution(object):
  def validUtf8(self, data):
    """
    :type data: List[int]
    :rtype: bool
    """
    features = {0x00: 0, 0xc0: 1, 0xe0: 2, 0xf0: 3}
    masks = [0xf8, 0xf0, 0xe0, 0x80]
    new = True
    followed = 0
    i = 0
    while i < len(data):
      if new:
        followed = -1
        for mask in masks:
          if (data[i] & mask) in features:
            followed = features[data[i] & mask]
            break
        if followed == -1:
          return False
        elif followed != 0:
          new = False
        else:
          new = True
      else:
        if (data[i] & 0xc0) != 0x80:
          return False
        followed -= 1
        if followed == 0:
          new = True
      i += 1

    return followed == 0
class Solution(object):
  def getSum(self, num1, num2):
    """
    :type a: int
    :type b: int
    :rtype: int
    """
    ans = 0
    mask = 0x01
    carry = 0
    for i in range(0, 32):
      a = num1 & mask
      b = num2 & mask
      c = carry
      carry = 0
      if a ^ b != 0:
        if c == 1:
          carry = 1
        else:
          ans |= mask
      else:
        if a & mask > 0:
          carry = 1
        if c == 1:
          ans |= mask

      mask = mask << 1
    if ans > 0x7fffffff:
      return ans - 0xffffffff - 1
    return ans

你可能感兴趣的:(2019-11-24)