Skip to content
This repository was archived by the owner on Jan 23, 2024. It is now read-only.

Commit fce1796

Browse files
author
Lanh Hoang
committed
InterviewBit - Strings: Reverse The String solution and README
1 parent 4360d12 commit fce1796

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

Strings/Reverse_the_String/README.md

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Reverse the String
2+
3+
## Problem:
4+
[https://www.interviewbit.com/problems/reverse-the-string](https://www.interviewbit.com/problems/reverse-the-string)
5+
6+
Given an input string, reverse the string word by word.
7+
8+
Example:
9+
10+
**Input**
11+
```
12+
s = "the sky is blue"
13+
```
14+
15+
**Output:**
16+
```
17+
"blue is sky the"
18+
```
19+
20+
**NOTE:**
21+
22+
A sequence of non-space characters constitutes a word.
23+
24+
Your reversed string should not contain leading or trailing spaces, even if it is present in the input string.
25+
26+
If there are multiple spaces between words, reduce them to a single space in the reversed string.
27+
28+
## Approach:
29+
30+
One simple approach is a two-pass solution:
31+
32+
- First pass to split the string by spaces into an array of words
33+
- Second pass to extract the words in reversed order
34+
35+
We can do better in one-pass. While iterating the string in reverse order, we keep track the beginning and the end position of a word.
36+
37+
When we are at the beginning of a word, we append it.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# https://www.interviewbit.com/problems/reverse-the-string
2+
3+
# Python built-in function
4+
# class Solution:
5+
# # @param A : string
6+
# # @return string
7+
# def reverseWords(self, A):
8+
# A = A.split()
9+
# A.reverse()
10+
# return ' '.join(A)
11+
12+
# Reverse in space
13+
class Solution:
14+
# @param A : string
15+
# @return string
16+
def reverseWords(self, A):
17+
left = -1
18+
right = len(A) - 1
19+
res = ''
20+
while right >= 0:
21+
while right >= 0 and A[right] == ' ':
22+
right -= 1
23+
24+
res += ' '
25+
left = right
26+
27+
while left >= 0 and A[left] != ' ':
28+
left -= 1
29+
30+
res += A[left+1:right+1]
31+
right = left
32+
return res.strip()

0 commit comments

Comments
 (0)