Reverse a String - Java Interview Coding Challenge #3 [Java Brains]

Reverse a String - Java Interview Coding Challenge #3 [Java Brains]

Java Brains

4 года назад

112,557 Просмотров

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


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

Java Brains
Java Brains - 29.07.2019 18:51

Thanks for all the great comments: Couple of things:
1. Yes, using character array is an option. You can use that instead of StringBuffer to save from creating a gazillion strings
2. Don't go for recursion unless asked. My suggestion is to mentally evaluate which is the simpler option. Recursion adds a cognitive load to whoever will read code in the future. So, use it only if it makes the solution simpler and more elegant than the iterative approach.

Ответить
Kevin Vélez
Kevin Vélez - 23.09.2023 23:46

My solution?

package javaapplication21;

import java.util.Scanner;

public class JavaApplication21{

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);
System.out.println("WORD: ");
String word = scan.nextLine();

StringBuilder sb = new StringBuilder();
System.out.println(sb.append(word).reverse());

}
}

Ответить
Ngoni Mugandani
Ngoni Mugandani - 21.02.2023 15:55

private static String reverseString(String s){
char [] n = new char[s.length()];
int counter = 0;
for (int i = s.length()-1; i > -1 ; i--) {
n[counter++]=s.toCharArray()[i];
}
return new String(n);
}

Ответить
Shubhasish Bhunia
Shubhasish Bhunia - 01.11.2022 23:19

String str = "Hello World";

char[] strCharArr = str.toCharArray();

for(int i = 0, k= strCharArr.length-1;i != k; i++, k--) {
char temp = strCharArr[i];
strCharArr[i] = strCharArr[k];
strCharArr[k] = temp;
}

System.out.println(String.valueOf(strCharArr));

Ответить
Tech_With_Vithal
Tech_With_Vithal - 24.10.2021 15:05

thank u sir

Ответить
Kazanaki HD
Kazanaki HD - 14.09.2021 19:45

and how to check if they are palindrome foe example Anna and Reversed Anna is the same thing how to check this.. maybe with str1.equals(str2) something like this?

Ответить
Nandan Kaushik
Nandan Kaushik - 23.07.2021 11:47

How are you able to write like pen on paper , on whiteboard which seems to be running on your system ?

Ответить
Veg Ahimsa
Veg Ahimsa - 25.06.2021 11:40

StringBuilder.reverse is about 10x faster than String += charAt().
StringBuilder is only a bit faster than StringBuffer on my computer.

StringBuilder.reverse: (200 - 512 - 4041) ns
StringBuffer.reverse: (230 - 566 - 4442) ns
char[] reversing outer to inner: (422 - 1325 - 8646) ns
String += charAt() for end to 0: (1277 - 5667 - 29 834) ns

Ответить
Veg Ahimsa
Veg Ahimsa - 25.06.2021 08:36

Create a char[] .

Ответить
TomarSahab
TomarSahab - 04.06.2021 09:51

Swap char from 0 to length -1

Ответить
Hùng Nguyễn
Hùng Nguyễn - 25.04.2021 09:22

Thanks, it's perfect explanation

Ответить
mahvish kalam
mahvish kalam - 07.04.2021 00:33

This is crap coding style, in fact bad programming, I have made better than this code see below,
public class Reverse {

public static void main(String[] args)
{

String rt="Hello World";
String result=rever(rt);
System.out.println(result);

}

static String rever(String str) {
StringBuffer obj=new StringBuffer();
for(int i=str.length()-1;i>=0;i--)
{
obj.append(str.charAt(i));
}
return obj.toString();


}
}

Ответить
Deepthi Warrier
Deepthi Warrier - 09.02.2021 02:29

Couldnt we also use stack and just print out the reversed string?

Ответить
The Blind Programmer
The Blind Programmer - 04.02.2021 03:11

Good vid, keep up the good work.

Ответить
ali ali
ali ali - 16.09.2020 03:12

I would use recorgen🤔 much faster

Ответить
SuperYouthful
SuperYouthful - 10.09.2020 23:00

Int[] StringArray = String.toArray(numString);
String revString = new String("");
For(int I = StringArray.length -1, I--, I >=0) {
RevString += ("" + StringArray[i] );
}
Return RevString;

Ответить
Younes Belbaz
Younes Belbaz - 10.09.2020 22:14

const reverseString = function (string) {
let j = string.length - 1;
let newString = "";
for (let i = string.length; i != 0; --i) {
newString += string.slice(j, i);
--j;
}
console.log(newString);
}
reverseString("Hello friends !");

Ответить
Edgie Ace Pojadas
Edgie Ace Pojadas - 02.09.2020 15:04

Back in my college days, all I did with this kind of problem is that I just put the string on an array and call the array in reverse, well I don't know if it's efficient thou, but it works and got some grade for it. lol

Ответить
Pushpesh Kumar
Pushpesh Kumar - 10.06.2020 19:20

I would love to see this series going for solving 50 such questions...

Ответить
RR
RR - 17.05.2020 14:21

Hi Koushik Cold you please add a tutorial to write a program that reverses a sentence. Ex: Hello World to World Hello

Ответить
David Parker
David Parker - 26.02.2020 10:32

Your manual solution is incorrect and it stems from a common misunderstanding of how strings are represented in Java. In Java, Strings are encoded using UTF-16, so you should preserve the relative ordering of UTF-16 surrogate pairs, i.e. this method fails to correctly reverse a string of code points outside of the basic multilingual plane, for example, emoji characters. In Java, the StringBuilder class already accounts for this if you use the reverse() method, so you should compare its output to your manual reverse on a string of emoji characters, or perhaps Egyptian hieroglyphs.

Ответить
MaLin Malindić
MaLin Malindić - 22.02.2020 20:44

Very nice way to find out , is a String a palindrome

Ответить
One Step Ahead
One Step Ahead - 19.12.2019 16:32

I think as Indian u should also speak hindi,

Ответить
MetinCloup
MetinCloup - 06.12.2019 21:22

This is more practical
package reverse;

public class reversAString {

public static void main(String[] args) {
String a= "hello";

for (int i=a.length()-1; i >= 0; i--) {
char c = a.charAt(i);
System.out.print(c);
}
}
}

Ответить
Upen Rajkumar
Upen Rajkumar - 19.11.2019 22:37

It would be great if you could also mention the BigO for the solution. Thanks so much

Ответить
Yuvaraj
Yuvaraj - 15.11.2019 08:43

sir can you upload more questions asked on interviews in java please!
thanks!

Ответить
Sisi M
Sisi M - 30.10.2019 05:18

These interview questions are soo helpful. So helpful that I landed an offer from Amazon! Thank you!! So much.

Ответить
Toufiqur Rahman
Toufiqur Rahman - 15.09.2019 11:25

please continue this series <3 from Bangladesh

Ответить
Sascha Broich
Sascha Broich - 02.09.2019 22:44

Did you check if this is working with upper Unicode characters? I think one would have to use code points. Otherwise emoticons and such would break.

Ответить
ariel
ariel - 31.08.2019 16:26

Please make a Java course

Ответить
Sebastian Mendoza
Sebastian Mendoza - 30.08.2019 07:34

Nice explanation. Some other ways I think this could be done is recurssion going from both ends to the center O(n/2). Another really easy way is to just use a stack, it would automatically return anything in it in reverse order once it is emptied.

Ответить
khadija bensaid
khadija bensaid - 26.08.2019 12:17

Thanks a lot

Ответить
Ricardo Rodríguez
Ricardo Rodríguez - 26.08.2019 06:27

Excellent video. Here’s my like 👍🏼

Ответить
Ritesh B
Ritesh B - 25.08.2019 18:04

Nice code sir👌

Ответить
Tushar Kshirsagar
Tushar Kshirsagar - 24.08.2019 08:41

You are not just teacher, but an incredible teacher... Thanks Kaushik...!!!

Ответить
Chetan Khandave
Chetan Khandave - 13.08.2019 14:18

Very good explanation. I try something different please have a look.
public static void reverseStringBuffer(StringBuffer sb)
{
int beginning = 0;
int end = sb.length()-1;
for(; beginning<end; beginning++, end--)
{
char c = sb.charAt(beginning);
sb.setCharAt(beginning, sb.charAt(end));
sb.setCharAt(end, c);
}
}

Another method using array of char is as follows
private static String reverseStringManually(String str1)
{
char[] charArray = str1.toCharArray();
char newCharArray [] = new char[charArray.length];
for(int i = charArray.length -1 , k = 0; i >= 0 ; i--, k++)
{
newCharArray[k] = charArray[i];
}
return new String(newCharArray);
}

Ответить
Ranjan Jha
Ranjan Jha - 12.08.2019 06:40

Expected to discuss most efficient approach

Ответить
Sidharth K. Burnwal
Sidharth K. Burnwal - 11.08.2019 21:28

keep making these kinds of videos brother :-)

Ответить
Finn
Finn - 09.08.2019 04:51

You're an amazing teacher .❤️
Please continue this series with frequent uploads.

Ответить
gs
gs - 07.08.2019 15:03

Thank you, Sir!!!!

Ответить
Arunabh Hejib
Arunabh Hejib - 06.08.2019 21:54

Hi Kaushik, how about making videos on currently hot topics like Kafka, Rabbit MQ, Cassandra. Messaging frameworks and NoSQL databases? That would be really helpful. Thanks!

Ответить
Pradip Talekar
Pradip Talekar - 04.08.2019 16:19

Hi Kaushik, really appreciate your work.

Thank you!!
Expecting more in this series - coding challenges

Ответить
Paul
Paul - 04.08.2019 01:54

These are really awesome, thanks for the good videos.

Ответить
Chiranjeevi Saride
Chiranjeevi Saride - 03.08.2019 04:04

Lol which tech company asks String Reverse in coding interview then interviewer is dumb

Ответить
Samwil Gost
Samwil Gost - 03.08.2019 02:52

Please Please more of these interview questions, I love the way you explain them!!!

Ответить
Nazar Lelyak
Nazar Lelyak - 01.08.2019 22:20

Also possible option is:
private static String reverseString(String str) {
StringBuilder builder = new StringBuilder();
for (int i = str.length(); i > 0; i--) {
builder.append(str.substring(i - 1, i));
}
return builder.toString();
}

Ответить
vinodkmr
vinodkmr - 01.08.2019 17:22

Hi Koushik,
Can you do a video on hash map implementation??

Ответить
Dante Astudillo
Dante Astudillo - 01.08.2019 07:52

return "oso" == new StringBuilder("oso").Reverse().toString()? true : false

Ответить
amirthasaha
amirthasaha - 31.07.2019 03:10

Thank you very much Koushik sir. you just rock in your teaching style. Please make courses on Core java concepts, Design patterns, Data Structure/Algorithms sir. Java Brains will become one stop for every Java Programmer from the beginner till whatever is the highest level. Thank you so so much sir.

Ответить