【算法】算法题-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)
相关推荐
李高钢14 小时前
Python FastAPI 框架入门:从零搭建你的第一个高性能 API 服务
数据库·python·fastapi
ocean210315 小时前
2025-2026年Python面试高频知识点洞察
开发语言·python·面试·python八股文
Warson_L15 小时前
Python的OrderedDict
python
stolentime15 小时前
洛谷P10515 转圈题解
c++·算法·数学建模·贪心算法
隐擎fox15 小时前
高性能网络爬虫架构设计:基于 Python 的长连接复用与分布式会话池调度实践
分布式·python·网络协议·tcp/ip·高并发·网络爬虫、
Warson_L15 小时前
Python的TypedDict
python·langchain·llm
晓窗科技16 小时前
口碑好的AI基座服务商
大数据·人工智能·python
和裕16 小时前
蜂窝板 vs 七层瓦楞重型纸箱:大件工业设备运输性能与成本全对比
大数据·运维·网络·人工智能·算法
小灰灰搞电子16 小时前
Python 信号量详解:并发控制实战
python·信号量
衡石科技16 小时前
Data_Agent记忆机制与经验复用衡石分析智能体会话记忆与长期学习技术解析
人工智能·科技·学习·算法·企业级bi