본문 바로가기

열정가득한 개발자의 이야기/Javascript Algorithm

151. Reverse Words in a String (Javascript)

반응형

 

Hi!

I solved a LeetCode problem about strings.

It's categorized as a medium problem, but I found it not too difficult.

I tried solving it, and I succeeded!

Anyway, let me explain the problem description.

  1. Remove leading and trailing spaces.
  2. If there are multiple spaces between words, reduce them to a single space.
  3. The goal is not to reverse the string character by character, but to reverse it word by word.

 

My solution:

  1. I used the trim() method to remove leading and trailing spaces.
  2. To reverse the words, I converted the string into an array.
    • Ah! The trim() method can only be used on String types.
  3. I declared a variable to store the result.
  4. To iterate through the array and process each element, I used a for loop and an if statement.
  5. I removed all extra spaces in the array and added a single space after each word.
  6. This process leaves an extra space at the end of the final string, so I used the slice() method to remove it before returning the result.

 

I hope it is helpful to you

 

have a good one

반응형