Тёмный

15 min Java Coding Challenge - Reverse Words in a String 

Nihao, MrZhang
Подписаться 6 тыс.
Просмотров 60 тыс.
50% 1

Опубликовано:

 

19 сен 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 135   
@officialdeyj1440
@officialdeyj1440 2 года назад
One more Approach : Split the String sentence into String array based on white spaces. Reverse iterate over that String array and keep concatenating another result String with the "i"th String and a space and return the result.
@hakanpwg
@hakanpwg 4 года назад
Easier way: use the string tokenizer with space denim and print each token but backwards. if there are more than 1 space between the words u can first replace all multiple spaces with a single space(Object String replace method)
@pooblock4092
@pooblock4092 3 года назад
Whaaaaaat 😂 that is so complicated for no reason. You can just create an array split by spaces using the string and then use a for loop to print from highest index to the lowest. Let me know if I’m wrong haha.
@soap2315
@soap2315 3 года назад
extra space
@jakirodragon3845
@jakirodragon3845 6 лет назад
very nice channel, im sure many people will join competitive programming by seeing your content
@nihaomrzhang5286
@nihaomrzhang5286 6 лет назад
Thank you for your support! I will work hard to create great content!
@dorjderemnamsraijav5182
@dorjderemnamsraijav5182 5 лет назад
I think using functions in such simple task is not a challenge. I appreciate what u do man.
@nihaomrzhang5286
@nihaomrzhang5286 5 лет назад
THANK YOU!!!
@HaKazzaz
@HaKazzaz 5 лет назад
For all those who think he made things too complicated by not using split: This is about solving the problem without allocating any extra space. Split works on String which you need to create first from char[]. Also it returns an array of Strings. This is about working with the char[] and reversing indexes. So yeah split will work and probably be more readable but does not meet the conditions.
@nihaomrzhang5286
@nihaomrzhang5286 5 лет назад
THANK YOU!!!
@spectrouts695
@spectrouts695 4 года назад
//what about this..I am using split and it meet the condition import java.util.*; class TestClass { public static void main(String args[] ) throws Exception { Scanner sc = new Scanner(System.in); String test = sc.nextLine(); String arr[] = test.split(" "); String result = ""; for(int i=arr.length-1; i>=0; i--){ if(i==0) { result += arr[i]; break; } result+=arr[i]+" "; } System.out.println(result); } }
@HaKazzaz
@HaKazzaz 4 года назад
@@spectrouts695 Hi dude, Nope, this is pretty much the same solution all of the Python comments suggested :) You are solving a different problem as your input is a String instead of char[]. In addition you create an array of String for each line you get, which is exactly what he is avoiding. Are you familiar with big O notation? Not a good enough solution for this question my dude.
@spectrouts695
@spectrouts695 4 года назад
@@HaKazzaz hello bro, I am just send the code which shows the use of split() and also more readable. Here off course I am taking String as input but one can convert easily to String from char[]. I am not saying that his code is wrong but proving my point that we can also use split() to make it more readable. Thanks for your time.
@HaKazzaz
@HaKazzaz 4 года назад
​@@spectrouts695 I see. I guess I just misunderstood because you said "meets the condition" but the condition is to reverse words without any extra space (converting to String, and then splitting into an array is extra space).
@scarzsad7708
@scarzsad7708 6 лет назад
for the 1st example(reverse String) you could also do this: public static String reverseString(String word){ String result = ""; for(int i = word.length() - 1; i >= 0; i--){ result += word.charAt(i);; } return result; }
@SamiSabirIdrissi
@SamiSabirIdrissi 5 лет назад
bro.. this is the longest reverse string logic i ever seen lol
@BlueIsLeet
@BlueIsLeet 4 года назад
Because it's using only primitive types, not String
@swarnalibhattacharjee3659
@swarnalibhattacharjee3659 4 года назад
Here this code is too complicated.... here I have Done just like that as Java Does not have reverse() method_____________________--> public class ReverseStringLine { public static void main(String[] args) { String s="the sky is blue"; System.out.println(reverse(s)); } static String reverse(String s){ String result=""; String[] word=s.split(" "); for(int i=0;i
@nihaomrzhang5286
@nihaomrzhang5286 4 года назад
Good one!
@diskmaskin8824
@diskmaskin8824 3 года назад
This is how I did it. I recommend using StringBuilder, it's a really awesome tool to work with Strings. try (Scanner scan = new Scanner(System.in)) { System.out.println("Enter a string to be reversed: "); String s = scan.nextLine(); String[] words = s.split("\\s+"); StringBuilder sb = new StringBuilder(); for (int i = words.length - 1; i >= 0; i--) { if (i == 0) { sb.append(words[i]); } else { sb.append(words[i] + " "); } } System.out.println(" Reversed: " + sb.toString()); }
@TheSkepticSkwerl
@TheSkepticSkwerl 5 лет назад
This was my solution. I have been using java for 1 week. public class Solution { public String reverseWords(String s) { String[] stringSplit = s.split(" "); String ans = ""; for (int i = stringSplit.length -1; i >= 0; i--) ans = ans + " " + stringSplit[i]; return ans.trim().replaceAll("\\s+"," "); } }
@fani8166
@fani8166 5 лет назад
@TheSkepticSkwerl i think you miss the last point which says could you do it with out allocating extra space? Thus you can't allocate a new string array and use split method that is the only reason which makes this question a bit hard
@armandopaulino5461
@armandopaulino5461 2 года назад
String phrase = "the sky is blue"; String[] words = phrase.split(" "); Optional result = Arrays.asList(words) .stream() .reduce((w1, w2 ) -> (w2+" ").concat(w1)); System.out.println(result.get());
@tman7022
@tman7022 2 года назад
Clever!
@nihaomrzhang5286
@nihaomrzhang5286 2 года назад
Thank you!
@CodeCraftWithQubais
@CodeCraftWithQubais 5 лет назад
public class shaikaffan{ public static void main(String args[]){ String s1="the sky is blue"; String[] s2=s1.split(" "); for(int i=(s2.length-1);i>=0;i--) { System.out.print(s2[i]+" "); } } }
@BlueIsLeet
@BlueIsLeet 4 года назад
Too bad it's a char array not a string
@chaudharyzafar7465
@chaudharyzafar7465 4 года назад
I think the comment section need to learn their isn’t always one answer to a coding question 😂
@nihaomrzhang5286
@nihaomrzhang5286 4 года назад
Hahaha! Thank you!!!
@mrj9551
@mrj9551 4 года назад
You could've used strig tokenizer to extract each word and store in an array and reverse the array and print it.
@programming_and_snacks5192
@programming_and_snacks5192 5 лет назад
Came here for 4:39
@nihaomrzhang5286
@nihaomrzhang5286 5 лет назад
ProgrammingWithSid hahahahahaha
@DoggyTVSVK
@DoggyTVSVK 3 года назад
That was burp() function which returns “excuse me” String
@davidchazanas5096
@davidchazanas5096 Год назад
Beautiful solution
@theblindprogrammer
@theblindprogrammer 3 года назад
Thank you for sharing this with us. Really helpful tips.
@nihaomrzhang5286
@nihaomrzhang5286 3 года назад
Thank you so much!!!
@mohandgesmelkhalig7335
@mohandgesmelkhalig7335 6 лет назад
I think We can solve this using split function in Java and use for loop
@nihaomrzhang5286
@nihaomrzhang5286 6 лет назад
What if there are more than one space in between the words?
@ImranHussain-pv9eb
@ImranHussain-pv9eb 6 лет назад
Then first u can replace all space with single space.....
@jamespaz4103
@jamespaz4103 5 лет назад
@@nihaomrzhang5286 use regex/ delimiter i guess in split() "//s±"
@HaKazzaz
@HaKazzaz 5 лет назад
Split works on String which you need to create first from char[]. Also it returns an array of Strings and this is about working with the char[] without allocating any extra space. So yeah it will work and probably be more readable but does not meet the conditions.
@diskmaskin8824
@diskmaskin8824 3 года назад
@@nihaomrzhang5286 Regex. split("\\s+")
@davidmahbubi
@davidmahbubi 4 года назад
In Javascript, you just need several seconds to do that : 'blue is sky the'.split(' ').reverse().join(' ');
@nihaomrzhang5286
@nihaomrzhang5286 4 года назад
Good job lol
@jamashe
@jamashe 3 года назад
The languages for lazy pple lol😀. The problem is many do not know whats happening inside. You just gave the computer .reverse.join and it did all the work for you. Here, you are doing the job and its fun because you learn something.
@Deutriex
@Deutriex 2 года назад
In Python it’s straightforward: “blue is sky the”[::-1]
@mypc8870
@mypc8870 4 года назад
Asha and Amar are playing SpaceKings a video game. It is a two player game where the second player is the helper. Asha needs your help maximizing her gold while playing her favorite game. Both are facing N aliens. Asha and Amar are both at a single location and the aliens are in lined up in front of them. Asha and Amar take turns shooting the aliens, and she goes first. During her turn, Asha may choose any alien to shoot at (this means Asha may choose to skip a turn). During his turn, Amar always shoots the alien closest to him to help Asha maximize her gold. Asha and Amar can not shoot dead alien. If Asha shoots at an alien, its hit points are reduced by P. If Amar shoots at an alien, its hit points are reduced by Q. If an alien's hit points goes below 1, it is killed. The ith alien starts with Hi hit points. Asha is awarded Gi gold if her shot kills the ith alien, but none if Amar's shot kills it. What is the maximum amount of gold Asha can obtain? Input Each case begins with one line containing three space-separated integers representing P, Q and N. N lines then follow, with the ith line containing two space-separated integers representing Hi and Gi. The aliens are given in the order of their distance from Asha and Amar. In other words, Amar will shoot at the ith alien only if all aliens < i are dead. Output Maximum amount of gold that Asha can get Input 20 60 3 80 100 80 200 120 300 Output 500 Explanation Asha should give up the first alien. During her first two turns she should soften up the third alien bringing it down to 80 hp, allowing her to easily get the last shot on the second and the third aliens Input 50 60 2 40 100 40 90 Output 100 Input 50 60 2 40 100 40 200 Output 200 Input 50 100 2 60 100 60 200 Output 200 Input 50 400 2 60 100 190 200 Output 0 solve it plzz
@Klasican
@Klasican 5 лет назад
Hi Yusen, thank you for this great content. I have one question. Do you maybe know - when people are on live coding technical interviews of this type, do they need to solve this kind of problems completely from their head? Or it is allowed to check the answers on the internet? Regards.
@nihaomrzhang5286
@nihaomrzhang5286 5 лет назад
Klasican Sorry but i don’t think looking up on the internet would be an option.....
@armandopaulino5461
@armandopaulino5461 2 года назад
String frase = "the sky is blue"; String[] words = frase.split(" "); frase = ""; for(int i = (words.length-1); i > -1; i--){ frase += words[i]+" "; } frase = (frase+"@").replace(" @", ""); System.out.println(frase);
@prashant_pawar.21
@prashant_pawar.21 3 месяца назад
First convert into split and loop start from reverse
@codeWithIncredibleX
@codeWithIncredibleX 2 года назад
Incredible
@rodericajillca884
@rodericajillca884 6 лет назад
Coding skills 👏
@nihaomrzhang5286
@nihaomrzhang5286 6 лет назад
Roderica Jillca Thanks!
@NitishYadav-pl3rz
@NitishYadav-pl3rz 6 лет назад
Just split and store in string array And print it from last index . Not more than 5 min.. But u have done gud.
@nihaomrzhang5286
@nihaomrzhang5286 6 лет назад
Nitish Yadav thank you, Nitish! Thanks for watching and commenting!
@nmbshotcar
@nmbshotcar 2 года назад
its fine !!
@ImranHussain-pv9eb
@ImranHussain-pv9eb 6 лет назад
Why don't you first tokenize the string words then store it in an array and ...then display in the array elements in reverse order with space
@nihaomrzhang5286
@nihaomrzhang5286 6 лет назад
Imran Hussain Then the space complexity would be O(n). My solution is O(1).
@gameking2447
@gameking2447 Год назад
the easiest way for beginner without any extra methods package Programming; import java.util.Scanner; public class ReverseWordsInSentence { public static void main(String[] args) { try (Scanner in = new Scanner(System.in)) { System.out.print("Enter a sentence: "); String str = in.nextLine(); int len = str.length(); String word = ""; for (int i = len - 1; i >= 0; i--) { char c = str.charAt(i); if (c != ' ') { word = c + word; } else { System.out.print(word + " "); word = ""; } } System.out.print(word); // Print the last word } } } Please reply what do you think and if you have any better program than this please share
@kotto4416
@kotto4416 2 года назад
can somebody explain once again why -2?
@CrazyCoder-cc5rq
@CrazyCoder-cc5rq 5 лет назад
Hi my solution is : public static String rew(String words) { char[] charTab = words.toCharArray(); String tempWord = ""; words = ""; for(char ch : charTab) { if(ch != ' ') { tempWord=tempWord+String.valueOf(ch); }else { words = tempWord+" "+words; tempWord=""; } } words = tempWord+" "+words; return words; }
@alexander.paderin
@alexander.paderin 5 лет назад
split->lifo->profit
@STS232323
@STS232323 6 лет назад
Great video!
@nihaomrzhang5286
@nihaomrzhang5286 6 лет назад
STS232323 Thank you!
@Tokyo_Pessi
@Tokyo_Pessi 5 лет назад
I think you made this way more complicated than it could've been, the split function wouldve made things way easier
@sanatdas8659
@sanatdas8659 4 года назад
This guy took 10 min to do such a easy programme.
@nihaomrzhang5286
@nihaomrzhang5286 4 года назад
You're welcome to film yourself doing this question for less than 10 min :)
@techbarikcom
@techbarikcom 4 года назад
Thanks boy
@yanmeili9342
@yanmeili9342 5 лет назад
public String reverseWords(String s) { if(s==null || s.equals("") || s.equals(" ")){return "";} String after = s.trim().replaceAll(" +", " "); String words[] = after.split(" "); String rst = ""; for (int i = words.length - 1; i >= 0 ; i --) { rst += words[i] + " "; } return rst; }
@andreofriendly7545
@andreofriendly7545 3 года назад
Hai im from the future, which 2021, jk how about my solve public static void main(String[] args) { String a = "andreo friendly timorence manukoa"; String hasil[] = a.split(" "); String c; for (int i = 0; i < hasil.length; i++) { a = hasil[(hasil.length-1)-i]; System.out.print(a + " "); } }
@raghavbajaj1813
@raghavbajaj1813 5 лет назад
Split the string on white space character and exchange the words in array
@nihaomrzhang5286
@nihaomrzhang5286 5 лет назад
That’s a good solution but can you also implement the “exchange” method?
@tehleelmir4407
@tehleelmir4407 5 лет назад
where do u work Google?
@nihaomrzhang5286
@nihaomrzhang5286 5 лет назад
Amazon.
@spanakorzo
@spanakorzo 6 лет назад
StringRiffle@Reverse@StringSplit@"the sky is blue" -WL
@nihaomrzhang5286
@nihaomrzhang5286 6 лет назад
That's a good solution but I think in a real interview they would like to let you implement the functions.
@spanakorzo
@spanakorzo 6 лет назад
Don't re-invent the wheel dude
@nihaomrzhang5286
@nihaomrzhang5286 6 лет назад
Unfortunately, I know it doesn't make sense but the interviewers want you to reinvent wheels lol.
@yassineboujnah6387
@yassineboujnah6387 3 года назад
String csv = "Apple Google Samsung"; List stringList = Arrays.asList(csv.split(" ")); Collections.reverse(stringList); System.out.println(stringList); //this print [Samsung, Google, Apple]
@nihaomrzhang5286
@nihaomrzhang5286 3 года назад
Good job!
@makwanakartik3599
@makwanakartik3599 5 лет назад
Hiiiiiiii neeed help
@nihaomrzhang5286
@nihaomrzhang5286 5 лет назад
What’s up
@chillaxkidszone
@chillaxkidszone Год назад
this is not a good solution for a simple problem!
@yeahwhatever1536
@yeahwhatever1536 6 лет назад
Are you joking?? Good for an exercise for learning purposes but this 'challenge' can be completed in two lines of code.
@nihaomrzhang5286
@nihaomrzhang5286 6 лет назад
Great! You can make a video of that solution then :)
@backtoafrica895
@backtoafrica895 4 года назад
Bro just use Split the String by Spaces. One line of code. You are nuquing this problem.
@aminoumtp5984
@aminoumtp5984 5 лет назад
Bonjour une autre façon de faire et merci pour le tuto public static String reverse(String chaine) { String[] parts = chaine.split(" "); for(int i = 0; i < parts.length / 2; i++) { String temp = parts[i]; parts[i] = parts[parts.length - i - 1]; parts[parts.length - i - 1] = temp; } String chaine2 = String.join(" ", parts); System.out.println(chaine2); return chaine2; }
@piotrz9546
@piotrz9546 3 года назад
overcomplicated solution
@hhueston
@hhueston 6 лет назад
String line = "the sky is blue"; String reverse = ""; String[] splitLine = line.split(" "); for(String part: splitLine){ reverse = part + reverse; } return reverse;
@nihaomrzhang5286
@nihaomrzhang5286 6 лет назад
Good solution but this is not what the question wants you to do tho. First, you allocated new space for the string. Second, you did not modify the provided string.
@hhueston
@hhueston 6 лет назад
Yusen Zhang only watched the first 10 seconds of your video so assumed this was what the question was asking. I'm sure you could adapt my answer to fit however you like.
@nihaomrzhang5286
@nihaomrzhang5286 6 лет назад
James Berry But what if the string has consecutive spaces? Will it still work?
@lukejriddle1
@lukejriddle1 6 лет назад
.trim ?
@cap0nn
@cap0nn 6 лет назад
yes: public String reverse(String words) { String[] wordsArray = words.split(" "); String reverse = ""; for(String word : wordsArray) reverse = word + " " + reverse; return reverse.trim(); }
@ashurafreedan
@ashurafreedan 6 лет назад
I thought you did a nice job
@nihaomrzhang5286
@nihaomrzhang5286 5 лет назад
Thank you, Harb! Thanks for watching and subscribing:)
Далее
Google Coding Interview With A Competitive Programmer
54:17
Ромарио стал Ромой
00:46
Просмотров 173 тыс.
How to Install and Use an Adjustable TV Arm
00:18
Просмотров 821 тыс.
People Cling To Trees As Typhoon Slams Into Shanghai
00:34
Winning Facebook (Meta) Hacker Cup Qual Round 2022?
53:55
Winning Google Kickstart Round A 2020 + Facecam
17:10
Solve This Coding Problem and Win $200
8:06
Просмотров 2,4 млн
Java Coding Interview Practice on Pramp
58:31
Просмотров 73 тыс.
ASMR Programming - Coding Pacman - No Talking
1:21:19
Просмотров 2,7 млн
Ромарио стал Ромой
00:46
Просмотров 173 тыс.