Python每日一练(20230319)
目录
1. 有效的括号 ★
2. 简化路径 ★★
3. 整数转换英文表示 ★★★
1. 有效的括号
给定一个只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串 s
,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
示例 1:
输入:s = "()" 输出:true
示例 2:
输入:s = "()[]{}" 输出:true
示例 3:
输入:s = "(]" 输出:false
示例 4:
输入:s = "([)]" 输出:false
示例 5:
输入:s = "{[]}" 输出:true
提示:
1 <= s.length <= 10^4
s
仅由括号'()[]{}'
组成
出处:
https://edu.csdn.net/practice/23155480
代码:
class Solution:
def isValid(self, s: str) -> bool:
parentheses = [
'(', '[', '{',
')', ']', '}'
]
i = 0
sum = [0, 0, 0]
top = []
while i < len(s):
c = s[i]
j = 0
while j <= 2:
if c == parentheses[j]:
top.append(j)
sum[j] += 1
elif c == parentheses[j+3]:
if len(top) == 0 or top[len(top)-1] != j:
return False
top.pop()
sum[j] -= 1
j += 1
i += 1
if sum[0] != 0 or sum[1] != 0 or sum[2] != 0:
return False
else:
return True
# %%
s = Solution()
print(s.isValid(s = "()[]{}"))
print(s.isValid(s = "(]"))
print(s.isValid(s = "([)]"))
print(s.isValid(s = "{[]}"))
输出:
True
False
False
True
进阶:
class Solution:
def isValid(self, s: str) -> bool:
stack = []
for c in s:
if c in ['(', '[', '{']:
stack.append(c)
else:
if not stack:
return False
if c == ')' and stack.pop() != '(':
return False
if c == ']' and stack.pop() != '[':
return False
if c == '}' and stack.pop() != '{':
return False
return not stack
# %%
s = Solution()
print(s.isValid(s = "()[]{}"))
print(s.isValid(s = "(]"))
print(s.isValid(s = "([)]"))
print(s.isValid(s = "{[]}"))
2. 简化路径
给你一个字符串 path
,表示指向某一文件或目录的 Unix 风格 绝对路径 (以 '/'
开头),请你将其转化为更加简洁的规范路径。
在 Unix 风格的文件系统中,一个点(.
)表示当前目录本身;此外,两个点 (..
) 表示将目录切换到上一级(指向父目录);两者都可以是复杂相对路径的组成部分。任意多个连续的斜杠(即,'//'
)都被视为单个斜杠 '/'
。 对于此问题,任何其他格式的点(例如,'...'
)均被视为文件/目录名称。
请注意,返回的 规范路径 必须遵循下述格式:
- 始终以斜杠
'/'
开头。 - 两个目录名之间必须只有一个斜杠
'/'
。 - 最后一个目录名(如果存在)不能 以
'/'
结尾。 - 此外,路径仅包含从根目录到目标文件或目录的路径上的目录(即,不含
'.'
或'..'
)。
返回简化后得到的 规范路径 。
示例 1:
输入:path = "/home/" 输出:"/home" 解释:注意,最后一个目录名后面没有斜杠。
示例 2:
输入:path = "/../" 输出:"/" 解释:从根目录向上一级是不可行的,因为根目录是你可以到达的最高级。
示例 3:
输入:path = "/home//foo/" 输出:"/home/foo" 解释:在规范路径中,多个连续斜杠需要用一个斜杠替换。
示例 4:
输入:path = "/a/./b/../../c/" 输出:"/c"
提示:
1 <= path.length <= 3000
path
由英文字母,数字,'.'
,'/'
或'_'
组成。path
是一个有效的 Unix 风格绝对路径。
出处:
https://edu.csdn.net/practice/23155482
代码:
class Solution(object):
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
result = []
plist = path.split('/')
for pos in plist:
if pos:
if pos == '..':
try:
result.pop()
except:
result = []
elif pos != '.':
result.append(pos)
return '/'+'/'.join(result)
# %%
s = Solution()
print(s.simplifyPath(path = "/home/"))
print(s.simplifyPath(path = "/../"))
print(s.simplifyPath(path = "/home//foo/"))
print(s.simplifyPath(path = "/a/./b/../../c/"))
代码2:
class Solution:
def simplifyPath(self, path: str) -> str:
def simplify(path_list):
stack = []
for p in path_list:
if p == '..':
if stack:
stack.pop()
elif p != '.' and p:
stack.append(p)
return '/' + '/'.join(stack)
return simplify(path.split('/'))
# %%
s = Solution()
print(s.simplifyPath(path = "/home/"))
print(s.simplifyPath(path = "/../"))
print(s.simplifyPath(path = "/home//foo/"))
print(s.simplifyPath(path = "/a/./b/../../c/"))
输出:
/home
/
/home/foo
/c
3. 整数转换英文表示
将非负整数 num
转换为其对应的英文表示。
示例 1:
输入:num = 123 输出:"One Hundred Twenty Three"
示例 2:
输入:num = 12345 输出:"Twelve Thousand Three Hundred Forty Five"
示例 3:
输入:num = 1234567 输出:"One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
示例 4:
输入:num = 1234567891 输出:"One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"
提示:
0 <= num <= 2^31 - 1
出处:
https://edu.csdn.net/practice/23155481
代码:
class Solution(object):
def numberToWords(self, num):
"""
:type num: int
:rtype: str
"""
def helper(num):
n = int(num)
num = str(n)
if n < 100:
return subhelper(num)
else:
return ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"][int(num[0]) - 1] + " Hundred " + subhelper(num[1:]) if num[1:] != "00" else ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"][int(num[0]) - 1] + " Hundred"
def subhelper(num):
n = int(num)
l1 = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]
l2 = ["Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
l3 = ["Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
if n < 10:
return l1[int(num)]
if 10 <= n < 20:
return l2[n - 10]
if 20 <= n < 100:
return l3[int(num[0]) - 2] + " " + l1[int(num[1])] if num[1] != "0" else l3[int(num[0]) - 2]
res = ""
if num >= 1000000000:
res = helper(str(num)[0]) + " Billion"
if str(num)[1:4] != "000":
res += " " + helper(str(num)[1:4]) + " Million"
if str(num)[4:7] != "000":
res += " " + helper(str(num)[4:7]) + " Thousand"
if str(num)[7:] != "000":
res += " " + helper(str(num)[7:])
elif num >= 1000000:
res = helper(str(num)[:-6]) + " Million"
if str(num)[-6:-3] != "000":
res += " " + helper(str(num)[-6:-3]) + " Thousand"
if str(num)[-3:] != "000":
res += " " + helper(str(num)[-3:])
elif num >= 1000:
res = helper(str(num)[:-3]) + " Thousand"
if str(num)[-3:] != "000":
res += " " + helper(str(num)[-3:])
else:
return helper(str(num))
return res
# %%
s = Solution()
print(s.numberToWords(123))
print(s.numberToWords(1234))
print(s.numberToWords(1234567))
print(s.numberToWords(1234567891))
代码2:
class Solution:
def numberToWords(self, num: int) -> str:
if num == 0:
return 'Zero'
def to_words(n):
ones = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']
tens = ['', 'Ten', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']
teens = ['', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']
if n == 0:
return ''
elif n < 10:
return ones[n]
elif n < 20:
return teens[n % 10]
elif n < 100:
return tens[n // 10] + ' ' + to_words(n % 10)
elif n < 1000:
return ones[n // 100] + ' Hundred ' + to_words(n % 100)
elif n < 1000000:
return to_words(n // 1000) + ' Thousand ' + to_words(n % 1000)
elif n < 1000000000:
return to_words(n // 1000000) + ' Million ' + to_words(n % 1000000)
else:
return to_words(n // 1000000000) + ' Billion ' + to_words(n % 1000000000)
return to_words(num).strip()
# %%
s = Solution()
print(s.numberToWords(123))
print(s.numberToWords(1234))
print(s.numberToWords(1234567))
print(s.numberToWords(1234567891))
输出:
One Hundred Twenty Three
One Thousand Two Hundred Thirty Four
One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven
One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One
🌟 每日一练刷题专栏 🌟
✨ 持续,努力奋斗做强刷题搬运工!
👍 点赞,你的认可是我坚持的动力!
🌟 收藏,你的青睐是我努力的方向!
✎ 评论,你的意见是我进步的财富!
![]() | Golang每日一练 专栏 |
![]() | Python每日一练 专栏 |
![]() | C/C++每日一练 专栏 |
![]() | Java每日一练 专栏 |
相关文章
- Python使用tkinter组件Label显示简单数学公式
- 内网渗透之DCOM横向移动
- 以目标为导向的语义交流的共同语言——一个课程学习框架
- python爬虫前奏【成信笔记】
- HTML 5 File API:文件拖放上传功能
- 教你快速创建 Python 虚拟环境
- pyenv 实现Python多版本自由切换
- 用 Python 对 Excel文件进行批量操作
- Python - 接入钉钉机器人
- Python - 抓取 iphone13 pro 线下店供货信息并发送到钉钉机器人,最后设置为定时任务
- crontab - 解决 mac 下通过 crontab 设置了 Python 脚本的定时任务却无法运行
- [源码解析] PyTorch分布式(5) ------ DistributedDataParallel 总述&如何使用
- Python科普系列——类与方法(上篇)
- SAP对STO的交货单执行PGI,报错 -Fld selectn for mvmt type 643 acct 400020 differs
- Spring Boot 实现通用 Auth 认证的 4 种方式
- 盘点4种使用Python批量合并同一文件夹内所有子文件夹下的Excel文件内所有Sheet数据
- OushuDB 学习经验分享(三):技术特点
- Java和Python思维方式的不同之处
- Python中日志记录新技能
- 奥比中光Gemini OpenCV—Python使用