Skip to content

Commit 74edb51

Browse files
authored
Merge pull request #2101 from shreyash3087/add/leetcode-917
Docs: Added Solutions to Leetcode 917
2 parents 9e86581 + 9c233fd commit 74edb51

File tree

2 files changed

+238
-1
lines changed

2 files changed

+238
-1
lines changed

dsa-problems/leetcode-problems/0900-0999.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ export const problems = [
117117
problemName: "917. Reverse Only Letters",
118118
difficulty: "Easy",
119119
leetCodeLink: "https://leetcode.com/problems/reverse-only-letters",
120-
solutionLink: "#"
120+
solutionLink: "/dsa-solutions/lc-solutions/0900-0999/reverse-only-letters"
121121
},
122122
{
123123
problemName: "918. Maximum Sum Circular Subarray",
Lines changed: 237 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,237 @@
1+
---
2+
id: reverse-only-letters
3+
title: Reverse Only Letters
4+
sidebar_label: 0917 - Reverse Only Letters
5+
tags:
6+
- Two Pointers
7+
- String
8+
- Stack
9+
description: "This is a solution to the Reverse Only Letters problem on LeetCode."
10+
---
11+
12+
## Problem Description
13+
14+
Given a string `s`, reverse the string according to the following rules:
15+
16+
- All the characters that are not English letters remain in the same position.
17+
- All the English letters (lowercase or uppercase) should be reversed.
18+
19+
Return `s` after reversing it.
20+
21+
### Examples
22+
23+
**Example 1:**
24+
25+
```
26+
Input: s = "ab-cd"
27+
Output: "dc-ba"
28+
```
29+
**Example 2:**
30+
31+
```
32+
Input: s = "a-bC-dEf-ghIj"
33+
Output: "j-Ih-gfE-dCba"
34+
```
35+
36+
### Constraints
37+
38+
- $1 \leq s.length \leq 100$
39+
- `s` consists of characters with ASCII values in the range `[33, 122]`.
40+
- `s` does not contain `'\"'` or `'\\'`.
41+
42+
## Solution for Reverse Only Letters
43+
44+
## Approach: Stack of Letters
45+
### Intuition and Algorithm
46+
47+
Collect the letters of `S` separately into a stack, so that popping the stack reverses the letters. (Alternatively, we could have collected the letters into an array and reversed the array.)
48+
49+
Then, when writing the characters of `S`, any time we need a letter, we use the one we have prepared instead.
50+
51+
### Code in Different Languages
52+
53+
<Tabs>
54+
<TabItem value="cpp" label="C++">
55+
<SolutionAuthor name="@Shreyash3087"/>
56+
57+
```cpp
58+
class Solution {
59+
public:
60+
string reverseOnlyLetters(string S) {
61+
stack<char> letters;
62+
for (char c : S)
63+
if (isalpha(c))
64+
letters.push(c);
65+
66+
string ans;
67+
for (char c : S) {
68+
if (isalpha(c))
69+
ans += letters.top(), letters.pop();
70+
else
71+
ans += c;
72+
}
73+
74+
return ans;
75+
}
76+
};
77+
78+
```
79+
</TabItem>
80+
<TabItem value="java" label="Java">
81+
<SolutionAuthor name="@Shreyash3087"/>
82+
83+
```java
84+
class Solution {
85+
public String reverseOnlyLetters(String S) {
86+
Stack<Character> letters = new Stack();
87+
for (char c: S.toCharArray())
88+
if (Character.isLetter(c))
89+
letters.push(c);
90+
91+
StringBuilder ans = new StringBuilder();
92+
for (char c: S.toCharArray()) {
93+
if (Character.isLetter(c))
94+
ans.append(letters.pop());
95+
else
96+
ans.append(c);
97+
}
98+
99+
return ans.toString();
100+
}
101+
}
102+
```
103+
104+
</TabItem>
105+
<TabItem value="python" label="Python">
106+
<SolutionAuthor name="@Shreyash3087"/>
107+
108+
```python
109+
class Solution(object):
110+
def reverseOnlyLetters(self, S):
111+
letters = [c for c in S if c.isalpha()]
112+
ans = []
113+
for c in S:
114+
if c.isalpha():
115+
ans.append(letters.pop())
116+
else:
117+
ans.append(c)
118+
return "".join(ans)
119+
```
120+
</TabItem>
121+
</Tabs>
122+
123+
### Complexity Analysis
124+
125+
#### Time Complexity: $O(N)$
126+
127+
> **Reason**: where `N` is the length of `S`.
128+
129+
#### Space Complexity: $O(N)$
130+
131+
## Approach: Reverse Pointer
132+
### Intuition
133+
134+
Write the characters of `S` one by one. When we encounter a letter, we want to write the next letter that occurs if we iterated through the string backwards.
135+
136+
So we do just that: keep track of a pointer `j` that iterates through the string backwards. When we need to write a letter, we use it.
137+
138+
### Code in Different Languages
139+
140+
<Tabs>
141+
<TabItem value="cpp" label="C++">
142+
<SolutionAuthor name="@Shreyash3087"/>
143+
144+
```cpp
145+
#include <string>
146+
#include <cctype>
147+
#include <sstream>
148+
149+
class Solution {
150+
public:
151+
std::string reverseOnlyLetters(std::string S) {
152+
std::stringstream ans;
153+
int j = S.length() - 1;
154+
for (int i = 0; i < S.length(); ++i) {
155+
if (std::isalpha(S[i])) {
156+
while (!std::isalpha(S[j]))
157+
j--;
158+
ans << S[j--];
159+
} else {
160+
ans << S[i];
161+
}
162+
}
163+
164+
return ans.str();
165+
}
166+
};
167+
168+
```
169+
</TabItem>
170+
<TabItem value="java" label="Java">
171+
<SolutionAuthor name="@Shreyash3087"/>
172+
173+
```java
174+
class Solution {
175+
public String reverseOnlyLetters(String S) {
176+
StringBuilder ans = new StringBuilder();
177+
int j = S.length() - 1;
178+
for (int i = 0; i < S.length(); ++i) {
179+
if (Character.isLetter(S.charAt(i))) {
180+
while (!Character.isLetter(S.charAt(j)))
181+
j--;
182+
ans.append(S.charAt(j--));
183+
} else {
184+
ans.append(S.charAt(i));
185+
}
186+
}
187+
188+
return ans.toString();
189+
}
190+
}
191+
```
192+
193+
</TabItem>
194+
<TabItem value="python" label="Python">
195+
<SolutionAuthor name="@Shreyash3087"/>
196+
197+
```python
198+
class Solution(object):
199+
def reverseOnlyLetters(self, S):
200+
ans = []
201+
j = len(ans) - 1
202+
for i, x in enumerate(S):
203+
if x.isalpha():
204+
while not S[j].isalpha():
205+
j -= 1
206+
ans.append(S[j])
207+
j -= 1
208+
else:
209+
ans.append(x)
210+
211+
return "".join(ans)
212+
```
213+
</TabItem>
214+
</Tabs>
215+
216+
### Complexity Analysis
217+
218+
#### Time Complexity: $O(N)$
219+
220+
> **Reason**: where `N` is the length of `S`.
221+
222+
#### Space Complexity: $O(N)$
223+
224+
## Video Solution
225+
226+
<LiteYouTubeEmbed
227+
id="M2TwbZCpJpw"
228+
params="autoplay=1&autohide=1&showinfo=0&rel=0"
229+
title="LeetCode Reverse Only Letters Solution Explained - Java"
230+
poster="hqdefault"
231+
webp />
232+
233+
## References
234+
235+
- **LeetCode Problem**: [Reverse Only Letters](https://leetcode.com/problems/reverse-only-letters/description/)
236+
237+
- **Solution Link**: [Reverse Only Letters](https://leetcode.com/problems/reverse-only-letters/solutions/)

0 commit comments

Comments
 (0)