Study Plan For Algorithms - Part15

1. 两数相除
给定两个整数,被除数 dividend 和除数 divisor。将两数相除,要求 不使用 乘法、除法和取余运算。
整数除法应该向零截断,也就是截去(truncate)其小数部分。例如,8.345 将被截断为 8 ,-2.7335 将被截断至 -2 。
返回被除数 dividend 除以除数 divisor 得到的 商 。

class Solution:
    def divide(self, dividend: int, divisor: int) -> int:
        if divisor == 0:
            raise ValueError("除数不为0")

        sign = (dividend < 0) ^ (divisor < 0)
        dividend = abs(dividend)
        divisor = abs(divisor)

        quotient = 0
        while dividend >= divisor:
            temp_divisor = divisor
            multiple = 1
            while dividend >= (temp_divisor << 1):
                temp_divisor <<= 1
                multiple <<= 1
            dividend -= temp_divisor
            quotient += multiple

        if sign:
            quotient = -quotient

        if quotient > 2**31 - 1:
            return 2**31 - 1
        elif quotient < -2**31:
            return -2**31
        else:
            return quotient

2. 串联所有单词的子串
给定一个字符串 s 和一个字符串数组 words。 words 中所有字符串 长度相同。
s 中的 串联子串 是指一个包含 words 中所有字符串以任意顺序排列连接起来的子串。
返回所有串联子串在 s 中的开始索引。

from collections import Counter

class Solution:
    def findSubstring(self, s: str, words: List[str]) -> List[int]:
        if not s or not words:
            return []

        word_length = len(words[0])
        total_length = len(words) * word_length
        word_counts = Counter(words)
        result = []

        for i in range(len(s) - total_length + 1):
            current_words = [s[i + j * word_length: i + (j + 1) * word_length] for j in range(len(words))]
            current_counts = Counter(current_words)

            if current_counts == word_counts:
                result.append(i)

        return result
posted @ 2024-08-29 06:42  WindMay  阅读(4)  评论(0编辑  收藏  举报