【算法】算法题-20231114

这里写目录标题

一、LCR 181. 字符串中的单词反转

单词 是由非空格字符组成的字符串。s 中使用至少一个空格将字符串中的 单词 分隔开。

返回 单词 顺序颠倒且 单词 之间用单个空格连接的结果字符串。

注意:输入字符串 s中可能会存在前导空格、尾随空格或者单词间的多个空格。返回的结果字符串中,单词间应当仅用单个空格分隔,且不包含任何额外的空格。

示例 1:

输入:s = "the sky is blue"

输出:"blue is sky the"

示例 2:

输入:s = " hello world "

输出:"world hello"

解释:反转后的字符串中不能存在前导空格和尾随空格。

示例 3:

输入:s = "a good example"

输出:"example good a"

解释:如果两个单词间有多余的空格,反转后的字符串需要将单词间的空格减少到仅有一个。

python 复制代码
def test6(s):
    return ' '.join(s.split(" ")[::-1])

s = "the sky is blue"
print(test6(s))

二、557. 反转字符串中的单词 III

给定一个字符串s,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。

示例 1:

输入:s = "Let's take LeetCode contest"

输出:"s'teL ekat edoCteeL tsetnoc"

示例 2:

输入: s = "God Ding"

输出:"doG gniD"

python 复制代码
def test7(s):
    return ' '.join([item[::-1] for item in s.split(" ")])

print(test7(s))

三、344. 反转字符串

编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 s 的形式给出。

给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。

示例 1:

输入:s = "h","e","l","l","o"

输出:"o","l","l","e","h"

示例 2:

输入:s = "H","a","n","n","a","h"

输出:"h","a","n","n","a","H"

python 复制代码
def test8(s):
    for i in range(len(s) // 2):
        s[i], s[len(s) - 1 - i] = s[len(s) - 1 - i], s[i]
    return s


s = ["H", "a", "n", "n", "a", "h"]
print(test8(s))

四、给定一个已按照升序排列的有序数组,找到两个数使得它们相加之和等于目标数。

给定一个已按照升序排列的有序数组,找到两个数使得它们相加之和等于目标数。

函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。

输入: numbers = 2, 7, 11, 15, target = 9

输出: 1,2

解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。

python 复制代码
def test9(nums, target):
    left = 0
    right = len(nums) - 1
    while left < right:
        if nums[left] + nums[right] == target:
            return [nums[left], nums[right]]
        elif nums[left] + nums[right] > target:
            right -= 1
        else:
            left += 1
    return [-1, -1]


nums = [2, 7, 11, 15]
target = 10
print(test9(nums, target))

五、力扣第49题:字母异位词分组

给你一个字符串数组,请你将字母异位词组合在一起。可以按任意顺序返回结果列表。

字母异位词是由重新排列源单词的字母得到的一个新单词,所有源单词中的字母通常恰好只用一次。

示例 1:

输入: strs = "eat", "tea", "tan", "ate", "nat", "bat"

输出: \["bat","nat","tan","ate","eat","tea"]

示例 2:

输入: strs = ""

输出: \[""]

示例 3:

输入: strs = "a"

输出: \["a"]

python 复制代码
from collections import defaultdict

def test1(nums):
    d = defaultdict(list)
    for item in nums:
        key = ''.join(sorted(item))
        d[key].append(item)
    return list(d.values())


nums = ["eat", "tea", "tan", "ate", "nat", "bat"]
r = test1(nums)
print(r)
相关推荐
2601_967979122 小时前
初学者必知的Python中优雅的用法
python·枚举·初学者·优雅用法·字典解析
AI创界者4 小时前
Python 进阶实战(五十八章):配置热更新、优雅停机排空与高并发压测方案
人工智能·python·aigc
2601_967987377 小时前
python网络工程师自动化运维课程
python·正则表达式·网络工程师·模块·自动化运维
吴凡wudianmei7 小时前
给 LLM 套输出契约:校验失败怎么把错误回灌给模型
python·llm·agent
祺曦8 小时前
复现连续手语识别项目
python·手语识别·复现项目·corrnet
江润舟8 小时前
万物|炼器:从零手搓工业级旋转目标检测网络·卷7 —— OBB检测头与DFL解码(三)
人工智能·python·深度学习
AI创界者9 小时前
Python 进阶实战(五十六):KV Cache 驱逐闭环反馈与 Prefill / Decode 分离协同调度
人工智能·python·aigc
2601_967980119 小时前
Python - 变量作用域
python·闭包·变量作用域·nonlocal·嵌套函数
山楂树の11 小时前
Python 模块、包、面向对象编程
python