LC - Numbers of Segments in a String
문제
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;
};Author And Source
이 문제에 관하여(LC - Numbers of Segments in a String), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@goody/LC-Numbers-of-Segments-in-a-String저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)