Leetcode [Medium] 151 - Reverse Words in a String
LeetCode 151
Reverse Words in a String
문제
Given an input string, reverse the string word by word.
Example 1:
Input: "the sky is blue"
Output: "blue is sky the"
Example 2:
Input: "  hello world!  "
Output: "world! hello"
Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3:
Input: "a good   example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
Note:
- A word is defined as a sequence of non-space characters.
- Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
- You need to reduce multiple spaces between two words to a single space in the reversed string.
나의 코드
// 1 차
/**
 * @param {string} s
 * @return {string}
 */
var reverseWords = function (s) {
  return s
    .split(" ")
    .reduce((acc, c) => {
      if (c !== "") acc.unshift(c);
      return acc;
    }, [])
    .join(" ");
};
// unshift (O(N)) 를 없애야할 듯
// 2차
/**
 * @param {string} s
 * @return {string}
 */
const reverseWords = (s) => {
  let str = s.trim();
  let curWord = "";
  let answer = "";
  for (let i = 0; i < str.length; i++) {
    if (str[i] !== " ") {
      curWord += str[i];
    } else if (str[i] === " " && curWord !== "") {
      answer = " " + curWord + answer;
      curWord = "";
    }
  }
  return curWord + answer;
};
참고 코드
var reverseWords = function (s) {
  return s
    .split(" ")
    .filter((x) => x !== "")
    .reverse()
    .join(" ");
};
배운점
- 
    
문자열 += 연산의 효율이 좋지 못하다는 것을 알게 되었다.
- 나름대로 O(N) loop 으로 코드를 짰지만 참조코드의 배열 reverse 연산과 차이가 거의 없어 보임
 - 
        
문자열 += 할 바에는 배열 split , join 등을 잘 활용하는 것이 코드 가독성에 더 좋을 것 같다.
 - JavaScript 효율성에 대한 블로그 글 [링크]
 
 
Subscribe via RSS