Circular Sentence

We need to determine if a given sentence is circular, which means that the last character of each word matches the first character of the next word, and the last character of the last word matches the first character of the first word.

Here’s how you can do this:

  1. Split the sentence into words.
  2. Iterate through the words and compare the last character of the current word with the first character of the next word.
  3. Additionally, compare the last character of the last word with the first character of the first word.
  4. If any of the comparisons fail, return False.
  5. If all comparisons pass, return True.

Below is the code that applies these steps:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
    def isCircularSentence(self, sentence: str) -> bool:
        words = sentence.split()

        # Check if the last character of each word matches the first character of the next word
        for i in range(len(words) - 1):
            if words[i][-1] != words[i + 1][0]:
                return False

        # Check if the last character of the last word matches the first character of the first word
        if words[-1][-1] != words[0][0]:
            return False

        return True

Explanation:

  • words = sentence.split() splits the sentence into individual words.
  • The first for loop iterates through the words and compares the last character of the current word (words[i][-1]) with the first character of the next word (words[i + 1][0]). If they don’t match, the sentence is not circular, so it returns False.
  • After the loop, the code checks if the last character of the last word matches the first character of the first word. If they don’t match, it returns False.
  • If all the checks pass, the code returns True, indicating that the sentence is circular.