[JavaScript] leetCode : Reverse Words in a String
728x90

๋ฌธ์ œ

Given an input string s, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space.

Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.

 

๋ฌธ์ž์—ด s๊ฐ€ ์ฃผ์–ด์งˆ ๋•Œ ๋ฌธ์ž์—ด ์•ˆ์˜ ๋‹จ์–ด๋ฅผ ์—ญ์ˆœ์œผ๋กœ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
๋ฐ˜ํ™˜๋œ ๋ฌธ์ž์—ด์—๋Š” ํ•˜๋‚˜์˜ ๊ณต๋ฐฑ๋งŒ ์žˆ์–ด์•ผ ํ•œ๋‹ค.

 

 

ํ’€์ด

const reverseWords = function(s) {
   // split์œผ๋กœ ๋‚˜๋ˆˆ๋‹ค
    // ๊ณต๋ฐฑ์ด ์•„๋‹Œ ๊ฒƒ๋“ค๋งŒ ์ถ”๋ฆฐ๋‹ค
    // reverse()๋กœ ๋ฐ˜ํ™˜ํ•œ๋‹ค
    // join์œผ๋กœ ๊ณต๋ฐฑ ๋„ฃ๊ธฐ

  return s
    .split(' ')
    .filter((word) => word.length > 0) 
    .reverse()
    .join(' ');
};

๋ฐฐ์—ด์˜ ๋ฉ”์„œ๋“œ๋“ค์„ ์ต์ˆ™ํ•˜๊ฒŒ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด ์—ฌ๋Ÿฌ ๋ฉ”์„œ๋“œ๋ฅผ ์ด์šฉํ•ด๋ณด๋ ค ํ–ˆ๋‹ค.
์ƒ๊ฐํ•œ ๊ณผ์ •์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

  1. ๋ฌธ์ž์—ด์„ ๊ณต๋ฐฑ์„ ๊ธฐ์ค€์œผ๋กœ, split์„ ํ†ตํ•ด ๋ฐฐ์—ด๋กœ ์ชผ๊ฐ ๋‹ค.
  2. filter๋ฅผ ํ†ตํ•ด ๊ณต๋ฐฑ์ด ์•„๋‹Œ ๊ฒƒ๋“ค๋งŒ ์ถ”๋ ค๋‚ธ๋‹ค.
  3. reverse๋กœ ์ถ”๋ ค๋‚ธ ๋ฐฐ์—ด์„ ์—ญ์ˆœ์œผ๋กœ ๋งŒ๋“ ๋‹ค.
  4. join ๋ฉ”์„œ๋“œ๋กœ ๊ฐ๊ฐ์˜ ์š”์†Œ ์‚ฌ์ด์— ๊ณต๋ฐฑ์„ ์ถ”๊ฐ€ํ•ด์ค€๋‹ค.

์ด ๊ณผ์ •์˜ ํ’€์ด๋Š” O(n)์˜ ์‹œ๊ฐ„๋ณต์žก๋„๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๋‹ค.

 

 

๋‹ค๋ฅธ ํ’€์ด

function reverseWords(s) {
  const ret = [];
  let word = [];
  for (let i = 0; i < s.length; ++i) {
    if (s.charAt(i) === ' ') {
        // We found the space, put word in front (if there is any)
        word.length > 0 && ret.unshift(word.join(''));
        // Reset the current word
        word = [];
      }
    else {
      // Add characters to the current word
      word.push(s.charAt(i));
    }
  }
  // If there is current word exists, add it in front
  word.length > 0 && ret.unshift(word.join(''));
  return ret.join(' ');
};

์ด ํ’€์ด๋Š” ๋ฌธ์ž์—ด์—์„œ ํ•œ ๊ธ€์ž์”ฉ ๊ฐ€์ ธ์™€์„œ ๊ณต๋ฐฑ์ด ์•„๋‹ ๊ฒฝ์šฐ word ๋ฐฐ์—ด์— ๋ฌธ์ž์—ด์„ ๋„ฃ์–ด์„œ ๋‹จ์–ด๋ฅผ ๋งŒ๋“ค๊ณ ,
๊ณต๋ฐฑ์ผ ๊ฒฝ์šฐ ๋ฌธ์ž์—ด ์•ž์— ๊ณต๋ฐฑ์„ ๋„ฃ์–ด์ค€ ๊ฒƒ์„ ๊ฒฐ๊ณผ ๋ฐฐ์—ด์— ๋„ฃ๋Š” ๋ฐฉ์‹์ด๋‹ค.

์•„๋ž˜์—์„œ ์›๋ฌธ์„ ๋ณผ ์ˆ˜ ์žˆ๋‹ค.

https://leetcode.com/problems/reverse-words-in-a-string/discuss/975824/JavaScript-solution-(no-split-reverse-methods)

728x90

'๐Ÿ““ Algorithm > LeetCode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[JavaScript] leetCode : Single Number  (0) 2022.05.26
[JavaScript] leetCode : Implement strStr()  (0) 2022.05.12
[JavaScript] leetCode : Longest Common Prefix  (0) 2022.05.09
[JavaScript] leetCode : Linked List Cycle II  (3) 2022.05.03
[JavaScript] leetCode : Valid Mountain Array  (3) 2022.05.02