Reverse Words in a String | LeetCode 151 | C++, Java, Python

preview_player
Показать описание

**** Best Books For Data Structures & Algorithms for Interviews:**********
*****************************************************************************

July LeetCoding Challenge | Problem 15 | Reverse Words in a String | 15 July,
Facebook Coding Interview question,
google coding interview question,
leetcode,
Reverse Words in a String,
Reverse Words in a String c++,
Reverse Words in a String Java,
Reverse Words in a String python,
Reverse Words in a String solution,
151. Reverse Words in a String,

#CodingInterview #LeetCode #JulyLeetCodingChallenge #Google #Amazon #ReverseWords
Рекомендации по теме
Комментарии
Автор

string reverseWords(std::string s) {
int i = 0;
int n = s.length();
string ans;

while (i < n) {
while (i < n && s[i] == ' ') {
i++; // skip spaces
}
if (i >= n) break;
int j = i;
while (j < n && s[j] != ' ') {
j++; // find the end of the word
}
string word = s.substr(i, j - i); // extract the word
if (ans.empty()) {
ans = word; // if it's the first word, no need to add space
} else {
ans = word + " " + ans; // prepend the word
}
i = j; // move to the next word
}
return ans;
}

Nick-je
Автор

I CANT'T THANK YOU ENOUGH I WAS FRUSTRATED FROM AN HOUR OR SO, THANKYOU SO MUCH FOR IMPLEMENTING IT IN JAVA ASWELL😭😭😭😭😭😭

nishasao
Автор

Your vedios are really great. In this solution, we append and then copy result string in every iteration which is not optimal, TC will become O(n^2). It is better to start from end of input string, reverse each sub-string and then append it to result string, this will give us TC as O(n)

faisalrafi
Автор

The best video explanations I have seen so far.

kiranmayeedobbali
Автор

For java users here is the code


class Solution {
public String reverseWords(String s) {
char []str=s.toCharArray();
String result="", w="";
int n=s.length();
int i=0, j=0;
while(i<n)
{
while(i<n && str[i]==' ') i++;
j=i+1;
while(j<n && str[j]!=' ') j++;

if(j<=n)
{w=s.substring(i, j);

if(result.isEmpty())
{
result=""+w;
}
else result=w+" "+result;
}
i=j+1;
}
return result;
}

}

harsha
Автор

class Solution(object):
def reverseWords(self, s):
sp = s.strip().split()
res = ""
i, j=0, len(sp)-1
while i<j:
sp[i], sp[j]=sp[j], sp[i]
i+=1
j-=1
return " ".join(sp)

rohansangodkar
Автор

best video i have found on how to reverse an word
thank u sir...

sauravjha
Автор

If you need O(1) space sol:

class Solution {
public:
void reverseword(string &s, int i, int j){ //reverse string from i to j
while(i<j){
char t = s[i];
s[i++] = s[j];
s[j--] = t;
}
}
string reverseWords(string s) {
int i=0, j=0;
int l=0;
int len = s.size();

int wordcount = 0;

while(true){
while(i<len && s[i] == ' ') //skip spaces in front
i++;
if(i==len)
break;
if(wordcount) //add space between the middle words
s[j++] = ' ';
l=j;
while(i<len && s[i] != ' '){ //place the word at the starting, removing spaces
s[j] = s[i];
j++, i++;
}
reverseword(s, l, j-1); //reverse word
wordcount++;
}
s.resize(j); //resize s to smaller string after removing spaces
reverse(s.begin(), s.end()); //Finally, reverse entire string to get the result
return s;
}
};

ashishupadhyay
Автор

this is the only solution I found where internal methods are not used

shrirangjoshi
Автор

sir, can u add time complexity of every problem in your video that's really help!!

namangoyal
Автор

what is the point of writing 7th line python . when we placed a condition i<n

nagendrabommireddi
Автор

python
class Solution:
def reverseWords(self, s: str) -> str:
return " ".join(list(filter(lambda x: len(x)>0, s.split(" ")))[::-1])

MadlipzMarathi
Автор

I REALLY LIKED THE PART WHERE HE EXPLAINED THE CODE IN C++ AND PYTHON

_shubhamr.sharma
Автор

in the solution, line #10 should be int j=i for a single character string.
Also line #15 should be i=j if that falls true.

Nick-je
Автор

Excellent
Thank you very much
Changing the index value after spaces is like magic
Really awesome 😎

riyazahemed
Автор

What a nice and a easy explanation .
Thank you Sir.

sahisharma
Автор

Thank you. You did in a very clear way.

abeldaniel
Автор

Really you are the best!. Especially those python solutions

amitsaurabh
Автор

I am wondering can we use stringtok in this question? Yes, it will be space O(n) but can be solved quicker I guess!

somratdutta
Автор

At 3:12 'i' variable is looking for space and 'j' variable is looking for non space. Anybody Correct me if i am wrong?

MilanMVlogs