13
Huuugo
7y

"How would you reverse a string?"

One of the best Java interview questions I ever had! (no kidding)

Comments
  • 3
    @hube

    Good questions:
    - Could you name some examples of patterns used in the standard library?
    - How do Thread and Runnable correlate?
    - What was/is your best project so far?
    - How would you summarize REST / SOLID / OOP / <insert another theoretical paradigm here>?

    Bad questions :
    - Are services in Spring singletons?
    - Can you implement token authentication for us?
    - Have you worked with <insert small library here> before?
  • 1
    out = in[::-1]
  • 2
    @redstonetehnik we're talking Java here, not python :-P
  • 0
  • 0
    Out of curiosity what is the best way? I would loop through concatenating the last letter each time into a temp variable and then deleting that letter from the original string untill there were no letters left. But there has to be a better way right?
  • 1
    @eggory see post tag. I think that's the easiest and most correct way.

    Your approach has a few drawbacks. First, you would need to convert the string to a charArray or list in order to loop it. Unicode letters can be made of two chars, so changing the order here causes errors. A list on the other side is quite memory intensive. Concatenating strings is another bad idea, because strings are immutable and you would create a new temporary object on every single concatenation in the loop. BTW, you don't need to remove any letters. Just return the new string.
  • 0
    So does it turn it to an array reverse it and the back to string? Also for what I posted, in hindsight, there's really no need to delete the letter from the original
  • 1
    The implementation of reverse() in StringBuilder is around 30 lines long., by the way. Look into it if you're interested. It basically switches the last with the first character, then loops to the middle of the string. Surrogate characters are handled extra in the end.
Add Comment