[LeetCode] Circular Sentence

아르당·2026년 9월 15일

LeetCode

목록 보기
528/602
post-thumbnail

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

Problem

문장은 맨 앞이나 맨 뒤에 공백이 없고 단일 공백으로 구분되는 단어 리스트이다.

  • 예를 들어, "Hello World", "HELLO", "hello world hello world"는 모두 문장이다.

단어는 영어 소문자와 대문자로만 구성된다. 영어 대문자와 소문자는 서로 다른 것으로 간주된다.
문장이 다음과 같은 경우 순환적이라고 한다.

  • 문장 내 각 단어의 마지막 글자는 그 다음 단어의 첫 글자와 같다.
  • 마지막 단어의 마지막 문자는 첫 번째 단어의 첫 번째 문자와 같다.

예를 들어, "leetcode exercises sound delightful", "eetcode", "leetcode eats soul"는 모두 순환적인 문장이다. 그러나, "Leetcode is cool", "happy Leetcode", "I like Leetcode"는 모두 비순환적인 문장이다.
문자열 sentence가 주어졌을 때, 순환적이라면 true를 반환해라. 그렇지 않다면, false를 반환해라.

Example

#1
Input: sentence = "leetcode exercises sound delightful"
Output: true

#2
Input: sentence = "eetcode"
Output: true

#3
Input: sentence = "Leetcode is cool"
Output: false

Constraints

  • 1 <= sentence.length <= 500
  • sentence는 오직 영어 소문자와 대문자, 공백으로 구성된다.
  • sentence에서 단어는 단일 공백으로 구분된다.
  • 맨 앞과 맨 뒤에는 공백이 없다.

Solved

class Solution {
    public boolean isCircularSentence(String sentence) {
        if(sentence.charAt(0) != sentence.charAt(sentence.length() - 1)){
            return false;
        }

        int k = sentence.indexOf(" ");

        if(k == -1){
            return true;
        }

        while(k != -1){
            if(sentence.charAt(k - 1) != sentence.charAt(k + 1)){
                return false;
            }

            k = sentence.indexOf(" ", k + 1);
        }

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

0개의 댓글