Closed mah-shamim closed 2 hours ago
We need to verify two conditions:
Let's implement this solution in PHP: 2490. Circular Sentence
<?php
/**
* @param String $sentence
* @return Boolean
*/
function isCircularSentence($sentence) {
// Split the sentence into words
$words = explode(" ", $sentence);
// Loop through the words and check the circular condition
for ($i = 0; $i < count($words); $i++) {
// Get the last character of the current word
$lastChar = substr($words[$i], -1);
// Determine the next word (wrap around if we're at the last word)
$nextWord = $words[($i + 1) % count($words)];
// Get the first character of the next word
$firstChar = substr($nextWord, 0, 1);
// Check if the last character of the current word matches the first character of the next word
if ($lastChar !== $firstChar) {
return false;
}
}
return true;
}
// Test cases
$sentence1 = "leetcode exercises sound delightful";
$sentence2 = "eetcode";
$sentence3 = "Leetcode is cool";
echo isCircularSentence($sentence1) ? "true\n" : "false\n"; // Output: true
echo isCircularSentence($sentence2) ? "true\n" : "false\n"; // Output: true
echo isCircularSentence($sentence3) ? "true\n" : "false\n"; // Output: false
?>
explode(" ", $sentence)
to split the sentence into words.substr($words[$i], -1)
.%
) to wrap around to the first word.false
.true
.This code efficiently checks the circular condition for each word pair, making it simple and optimal.
Discussed in https://github.com/mah-shamim/leet-code-in-php/discussions/779