-
Notifications
You must be signed in to change notification settings - Fork 43
/
reverse-only-letters.py
92 lines (86 loc) · 2.27 KB
/
reverse-only-letters.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# V0
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/82956271
# IDEA : STACK
# STACK : FIRST IN, LAST OUT (LILO)
class Solution(object):
def reverseOnlyLetters(self, S):
"""
:type S: str
:rtype: str
"""
letters = []
N = len(S)
for i, s in enumerate(S):
if s.isalpha():
letters.append(s)
res = ""
for i, s in enumerate(S):
if s.isalpha():
res += letters.pop()
else:
res += s
return res
# V1'
# https://blog.csdn.net/fuxuemingzhu/article/details/82956271
# IDEA : SINGLE POINTER
class Solution(object):
def reverseOnlyLetters(self, S):
"""
:type S: str
:rtype: str
"""
N = len(S)
l = N - 1
res = ""
for i, s in enumerate(S):
if s.isalpha():
while not S[l].isalpha():
l -= 1
res += S[l]
l -= 1
else:
res += s
return res
# V1''
# https://blog.csdn.net/fuxuemingzhu/article/details/82956271
# IDEA : DOUBLE POINTER
class Solution(object):
def reverseOnlyLetters(self, S):
"""
:type S: str
:rtype: str
"""
N = len(S)
left, right = 0, N - 1
slist = list(S)
while left < right:
while left < N and (not S[left].isalpha()):
left += 1
while right >= 0 and (not S[right].isalpha()):
right -= 1
if left < N and right >= 0 and left < right:
slist[left], slist[right] = slist[right], slist[left]
left, right = left + 1, right - 1
return "".join(slist)
# V2
# Time: O(n)
# Space: O(1)
class Solution(object):
def reverseOnlyLetters(self, S):
"""
:type S: str
:rtype: str
"""
def getNext(S):
for i in reversed(range(len(S))):
if S[i].isalpha():
yield S[i]
result = []
letter = getNext(S)
for i in range(len(S)):
if S[i].isalpha():
result.append(letter.next())
else:
result.append(S[i])
return "".join(result)