Python 中仅反转字母
假设我们有一个字符串 S,我们需要找到一个反转后的字符串,其中所有不是字母的字符不会改变其位置,所有字母反转其位置。因此,如果给定的字符串是 "a-bC-dEf-ghIj",则输出将是 "j-Ih-gfE-dCba"
为了解决这个问题,我们将遵循以下步骤 -
- 我们将使用正则表达式库来解决这个问题
- 如果 S 为空,则返回 S
- str := 空字符串,index1 := 0 且 index2 := S 的长度 – 1
- 当 index1 < S 的长度
- 如果 index2 >= 0 且 S[index1] 为字母且 S[index2] 为字母
- str := str + S[index2]
- 将 index2 减 1,并将 index1 加 1
- 否则,如果 S[index1] 为字母,则将 index2 减 1
- 否则,如果 S[index1] 不是字母,则 str := str + S[index1],将 index1 加 1
- 否则,将 index2 减 1,并将 index1 加 1
- 如果 index2 >= 0 且 S[index1] 为字母且 S[index2] 为字母
- 返回 str
示例
让我们看看以下实现以获得更好的理解 -
class Solution:
def reverseOnlyLetters(self, S):
if not S:
return S
str_= ""
index1 = 0
index2 = len(S)-1
while index1<len(S):
#print(index1,index2)
if index2>=0 and S[index1].isalpha() and S[index2].isalpha():
str_+=S[index2]
index2 -= 1
index1 += 1
elif S[index1].isalpha():
index2-=1
elif not S[index1].isalpha():
str_+=S[index1]
index1+=1
else:
index2 -= 1
index1 += 1
return str_
ob1 = Solution()
print(ob1.reverseOnlyLetters("a-bC-dEf-ghIj"))输入
"a-bC-dEf-ghIj"
输出
"j-Ih-gfE-dCba"
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP