Home >Backend Development >PHP Tutorial >Circular Sentence
2490. Circular Sentence
Difficulty: Easy
Topics: String
A sentence is a list of words that are separated by a single space with no leading or trailing spaces.
Words consist of only uppercase and lowercase English letters. Uppercase and lowercase English letters are considered different.
A sentence is circular if:
For example, "leetcode exercises sound delightful", "eetcode", "leetcode eats soul" are all circular sentences. However, "Leetcode is cool", "happy Leetcode", "Leetcode" and "I like Leetcode" are not circular sentences.
Given a string sentence, return _true if it is circular_. Otherwise, return false.
Example 1:
Example 2:
Example 3:
Constraints:
Hint:
Solution:
We need to verify two conditions:
Let's implement this solution in PHP: 2490. Circular Sentence
Explanation:
- Splitting the Sentence: Use explode(" ", $sentence) to split the sentence into words.
- Looping through Words:
- For each word, get its last character using substr($words[$i], -1).
- Get the first character of the next word. For the last word, we use modulo (%) to wrap around to the first word.
- Comparison:
- If the last character of a word doesn’t match the first character of the next word, return false.
- If the loop completes without finding any mismatch, the sentence is circular, so return true.
This code efficiently checks the circular condition for each word pair, making it simple and optimal.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of Circular Sentence. For more information, please follow other related articles on the PHP Chinese website!