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

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

Knowledge Center

3 года назад

162,520 Просмотров

Ссылки и html тэги не поддерживаются


Комментарии:

Mr. Car Guy
Mr. Car Guy - 28.09.2023 06:54

Ultimate i would say hats off sir👌👌👏👏

Ответить
Nagendra Bommireddi
Nagendra Bommireddi - 30.08.2023 14:40

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

Ответить
Rohan Sangodkar
Rohan Sangodkar - 21.07.2023 18:20

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)

Ответить
Desi entertainment
Desi entertainment - 19.07.2023 09:03

EASIEST SOLUTION C++ NO EXTRA SPACE

string revWords(string s) {

int i=0;
while(i<s.size() && s[i]==' ')
{
i++;
}

int j=s.size()-1;
while(j>=0 && s[j]==' ')
{
j--;
}


int cnt=0;
string ans="";
string res="";



for(int x=i;x<=j;x++)
{
if(s[x]==' ')
{
cnt++;
continue;
}
if(cnt)
{
if(res=="")
{
res=ans;
}
else
{
res=ans+" "+res;
}
cnt=0;
ans="";
}
ans+=s[x];
}
res=ans+" "+res;
return res;
}

Ответить
Yann LilGrass
Yann LilGrass - 16.07.2023 00:05

I write a main method after your code. and it doesn't work. It only returns one word of my sentence.

public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);


System.out.println("Enter the sentence:");
String sentence = keyboard.next();
String result = reverseWords(sentence);
System.out.println(result);

}
Did I do anything wrong with my main method?

Ответить
Ishan Gujarathi
Ishan Gujarathi - 09.07.2023 10:42

thanks for the explanation!!

Ответить
Rutwik More
Rutwik More - 15.05.2023 17:26

Awesome explaination !!

Ответить
Saurav Jha
Saurav Jha - 21.03.2023 19:57

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

Ответить
vagabond foodie
vagabond foodie - 02.03.2023 06:09

Sir it is difficult for Me to understand the concept why we take subs from (i, j-i) why not from (i,j) in c++

Ответить
Manav Sadiwala
Manav Sadiwala - 20.02.2023 16:53

How to skip last two words in sentence?

My input string is: Hi there. My name is Kalp. This is my lucky day. I like coding so much. This is it.

Expected output is: Hi there. name My is Kalp. my is This lucky day. coding like I so much. This is it.

Ответить
TYCOC303_Harshil Huda
TYCOC303_Harshil Huda - 17.02.2023 13:44

Code for no extra space
class Solution {
public:
string reverseWords(string s) {
int k=s.size();
int n=k;
s+=" ";
while(n>=0)
{
while(n>=0 && s[n]==' ')
{
n--;
}
if(n<0) break;
int j=n-1;
while(j>=0 && s[j]!=' ')
{
j--;
}
s+=s.substr(j+1,n-j)+" ";
n=j-1;
}
s=s.substr(k+1,s.size()-(k+2));
return s;
}
};

Ответить
Stuti
Stuti - 11.02.2023 17:35

While(i<n&&s[i]==' '){
i++;
}
Why is it giving empty character constant error and empty expression error . Please tell . I have written the code exactly like u but it doesn't run

Ответить
Avixka
Avixka - 02.02.2023 01:04

This isn't working for me.
The output is:
"blue is sky the the"
"world hello hello"
"example good a a".

The output always duplicate the last word.

Edit*
Never mind, I miss-placed the i = j + 1 into the final else statement

Ответить
98_Shubham R. Sharma
98_Shubham R. Sharma - 11.01.2023 17:50

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

Ответить
laharish reddy
laharish reddy - 08.01.2023 13:41

commented using API.

Ответить
laharish reddy
laharish reddy - 08.01.2023 13:39

video are very helpful.

Ответить
Karol
Karol - 24.11.2022 13:08

s = sentence.split()[::-1]
l = []
for i in s:
l.append(i[::-1])
print('-'.join(l))

Ответить
imran immu
imran immu - 13.11.2022 13:00

Thank you, was very helpful

Ответить
Venu Gopal
Venu Gopal - 21.10.2022 05:29

Good video sir,
Can you write this Java program too:
Input: "This is, the most; particular example!"
Output: "example particular, most the; is This!"

Ответить
Sahaj Pareek
Sahaj Pareek - 10.10.2022 05:28

I don't understand why we can't just use trim in java and strip in python to get rid of the leading and trailing spaces.

Ответить
GM
GM - 03.10.2022 05:42

thanks.........

Ответить
Aflatoon
Aflatoon - 26.08.2022 11:48

How to write complext code 101

Ответить
Sharandeep Kaur
Sharandeep Kaur - 11.07.2022 21:46

can anyone tell what is the significance of writing if(i>=n)break; here?
it will be really helpful

Ответить
aman mishra
aman mishra - 16.06.2022 23:04

public static void test2() {
String str = " My name is Aman ";
StringBuilder strb = new StringBuilder(str);
String str2 = strb.reverse().toString();

int i=0; int j=0;
while(i<str2.length() && str2.charAt(i)==' ') {
i++;
}
String str3="";
while(j<str2.length()) {
j=i;
while(i<str2.length() && str2.charAt(i)!=' ') {
i++;
}

StringBuilder strb1 = new StringBuilder(str2.substring(j, i));
str3=str3+" "+strb1.reverse().toString();
i++;
System.out.println(str3);
}
System.out.println(str3);
}

Ответить
Varun Gupta
Varun Gupta - 30.05.2022 22:11

always try to show runtime speed and space after code is submitted

Ответить
Kwaku Kusi
Kwaku Kusi - 13.03.2022 14:54

thank you bro, your explanations are so clear

Ответить
Venu Gopal N
Venu Gopal N - 16.02.2022 08:46

In Leetcode, it gives error for Python3

Time Limit Exceeded

Ответить
Dante Nero
Dante Nero - 12.02.2022 07:14

this code is not working in leetcode

Ответить
faisal rafi
faisal rafi - 11.02.2022 04:27

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)

Ответить
Sagrika
Sagrika - 28.01.2022 13:56

Thanku sir

Ответить
Vikram Reddy
Vikram Reddy - 20.01.2022 13:54

Hi @Abhishek the video is very good, but I am thinking can we split the string using spaces and rearranging in the reverse order it will do our requirement right.

Ответить
Rakshit Koli
Rakshit Koli - 04.11.2021 22:16

C++ Code is not working

Ответить
Rami Aldarkazly
Rami Aldarkazly - 28.10.2021 07:20

Thanks

Ответить
SAMIIRR VIRAL STARR
SAMIIRR VIRAL STARR - 29.09.2021 15:52

please provide the desired code in description box

Ответить
Rajat Verma
Rajat Verma - 25.07.2021 16:00

Thank You Sir.

Ответить
Madlipz Marathi
Madlipz Marathi - 23.07.2021 13:32

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

Ответить
Somrat Dutta
Somrat Dutta - 12.07.2021 23:12

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

Ответить
Abhishek chaurasiya
Abhishek chaurasiya - 30.04.2021 16:47

Code is not reversing , please help

Ответить
Subham Agarwal
Subham Agarwal - 18.04.2021 06:57

Perfect

Ответить
Shubhankar Mane
Shubhankar Mane - 02.04.2021 09:01

Nice explanation

Ответить
Parthesh Soni
Parthesh Soni - 16.01.2021 09:13

Nice explanation. Although I was expecting in-place solution.

Ответить
abhishek suryavanshi
abhishek suryavanshi - 14.01.2021 20:46

Jaduu!

Ответить
Ashish Upadhyay
Ashish Upadhyay - 17.10.2020 17:09

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;
}
};

Ответить
Boston Lights
Boston Lights - 07.10.2020 19:33

Wow man... Quality content every time

Ответить
Abel Daniel
Abel Daniel - 23.09.2020 06:51

Thank you. You did in a very clear way.

Ответить
Amit Saurabh
Amit Saurabh - 05.09.2020 19:16

Really you are the best!. Especially those python solutions

Ответить
ehsan hosseini
ehsan hosseini - 18.08.2020 04:44

Excellent explanation

Ответить
Unv12sL
Unv12sL - 27.07.2020 00:32

Time complexity should be
O(n) We are still iterating through the array linearly, and when the j loop is activated,
it still linearly searches in the same array but when it reaches a letter/nospace until it reaches '_' (_ is 1 space). , then continues from outer main loop again, the inner loop if it satisfies the condition all the way to the end of len(array).

Space should be
O(n) since we create a result array, it cannot be O(1) because we are not manipulating the input array in place.

Please feel free to correct me if I'm wrong but I am thinking this is correct.

Ответить
Shubhanshu Singh
Shubhanshu Singh - 21.07.2020 23:37

Sir, there's no doubt that you make a problem look very easy but it will be great if you write code in C language also...plzzzzz

Ответить
Riyaz Ahemed
Riyaz Ahemed - 16.07.2020 21:42

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

Ответить