반응형
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.
- Remove leading and trailing spaces.
- If there are multiple spaces between words, reduce them to a single space.
- The goal is not to reverse the string character by character, but to reverse it word by word.
My solution:
- I used the trim() method to remove leading and trailing spaces.
- To reverse the words, I converted the string into an array.
- Ah! The trim() method can only be used on String types.
- I declared a variable to store the result.
- To iterate through the array and process each element, I used a for loop and an if statement.
- I removed all extra spaces in the array and added a single space after each word.
- 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
반응형
'열정가득한 개발자의 이야기 > Javascript Algorithm' 카테고리의 다른 글
1768. Merge Strings Alternately (JS) (0) | 2025.03.23 |
---|---|
1071. Greatest Common Divisor of Strings (JS) (0) | 2025.03.22 |
643. Maximum Average Subarray I with JS (0) | 2025.02.28 |
leetcode 575. Distribute Candies (javascript) (1) | 2025.01.27 |
500. Keyboard Row (javascript) (0) | 2025.01.26 |