[LeetCode] Number of Segments in a String

준규·2023년 3월 2일
0

1.문제


Given a string s, return the number of segments in the string.

A segment is defined to be a contiguous sequence of non-space characters.


문자열 s가 주어질 때 s의 segment의 개수를 리턴하는 문제이다.

이때 segment란 공백없이 이어지는 하나의 단어이다.


Example 1

Input: s = "Hello, my name is John"
Output: 5
Explanation: The five segments are ["Hello,", "my", "name", "is", "John"]

Example 2

Input: s = "Hello"
Output: 1

Constraints:

  • 0 <= s.length <= 300
  • s consists of lowercase and uppercase English letters, digits, or one of the following characters "!@#$%^&*()_+-=',.:".
  • The only space character in s is ' '.

2.풀이

  1. s를 공백기준으로 쪼개서 배열에 저장한다.
  2. 저장한 배열에서 ""를 제거한다.

/**
 * @param {string} s
 * @return {number}
 */
const countSegments = function (s) {
  //s를 공백기준으로 분리해서 배열로 만든 다음 배열에서 ""를 제거한다
  const result = s.split(" ").filter((item) => {
    return item !== "";
  });

  return result.length;
};

3.결과

profile
안녕하세요 :)

0개의 댓글