Skip to content

Commit 2de6782

Browse files
committed
feat: reverse-string
1 parent 110a8db commit 2de6782

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

str.longest-common-prefix.py

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
from typing import List
2+
3+
class Solution:
4+
"""
5+
14. 最长公共前缀
6+
https://leetcode-cn.com/problems/longest-common-prefix/
7+
编写一个函数来查找字符串数组中的最长公共前缀。
8+
如果不存在公共前缀,返回空字符串 ""。
9+
"""
10+
def longestCommonPrefix(self, strs: List[str]) -> str:
11+
if not strs:
12+
return ''
13+
14+
if len(strs) == 1:
15+
return strs[0]
16+
17+
res = ''
18+
first = strs[0]
19+
for s in range(len(strs[0])):
20+
for p in range(1, len(strs)):
21+
if s < len(strs[p]) and first[s] == strs[p][s]:
22+
continue
23+
else:
24+
return res
25+
res += first[s]
26+
return res
27+
28+
29+
so = Solution()
30+
print(so.longestCommonPrefix(["flower","flow","flight"]))

str.reverse-string.py

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
"""
6+
344. 反转字符串
7+
https://leetcode-cn.com/problems/reverse-string/
8+
编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。
9+
不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。
10+
你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。
11+
"""
12+
def reverseString(self, s: List[str]) -> None:
13+
14+
i = 0
15+
j = len(s) - 1
16+
while i < j:
17+
s[i], s[j] = s[j], s[i]
18+
i += 1
19+
j -= 1
20+
21+
print(s)
22+
23+
so = Solution()
24+
print(so.reverseString(["H","a","n","n","a","h"]))

0 commit comments

Comments
 (0)