[LeetCode] Number of Segments in a String

아르당·2026년 1월 15일

LeetCode

목록 보기
90/213
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

문자열 s가 주어졌을 때, 세그먼트의 개수를 반환해라.

세그먼트는 공백이 아닌 연속된 문자들의 시퀀스로 정의된다.

Example

#1
Input: s = "Hello, my name is John"
Output: 5
Explanation: 다섯 개의 세그먼트는 ["Hello,", "my", "name", "is", "John"]이다.

#2
Input: s = "Hello"
Output: 1

Constraints

  • 0 <= s.length <= 300
  • s는 소문자와 대문자 영어 알파벳, 숫자 또는 "!@#$%^&*()_+-=',.:" 문자 중 하나로 구성된다.
  • s에 있는 유일한 공백 문자는 ' '이다.

Solved

class Solution {
    public int countSegments(String s) {
        int count = 0;
        boolean inSegment = false;

        for(char c : s.toCharArray()){
            if(c != ' ' && !inSegment){
                count++;
                inSegment = true;
            }else if(c == ' '){
                inSegment = false;
            }
        }

        return count;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글