LC - Numbers of Segments in a String

Goody·2021년 2월 22일
0

알고리즘

목록 보기
49/122

문제

You are 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.


예시

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

Example 3:

Input: s = "love live! mu'sic forever"
Output: 4

Example 4:

Input: s = ""
Output: 0


풀이

  • 문자열 내 단어의 수를 구하는 문제이다.
  • 주어진 문자열을 split 메서드로 공백을 기준으로 나눈다.
  • 나눠진 문자열의 길이를 반환하되, 공백을 만나면 길이를 하나 줄인다.

코드

var countSegments = function(s) {
        let answer = 0;
    let segments = s.split(" ");
    answer = segments.length;
    segments.forEach((el) => {
        if(el === "") answer--;
    });

    return answer;
};

0개의 댓글