Leetcode 2490. Circular Sentence
You are given a sentence represented as a string s
consisting of lowercase English letters and spaces. A sentence can be considered a circular sentence if the last character of each word matches the first character of the next word. The last word should also match the first word to be categorized as a circular sentence.
Write a function isCircularSentence
that determines if the given sentence is circular.
Example 1:
Input: s = "leetcode exercises sound delightful"
Output: true
Explanation: The sentence "leetcode exercises sound delightful" is a circular sentence. The last character of each word matches the first character of the next word, and the last character of the sentence matches the first character of the first word.
Example 2:
Input: s = "eetcode"
Output: true
Explanation: The sentence "eetcode" is a circular sentence. The last character of the single word matches the first character of the same word.
Example 3:
Input: s = "Leetcode is cool"
Output: false
Explanation: The sentence "Leetcode is cool" is not a circular sentence because the last character of the word "Leetcode" is "e" and it does not match the first character of the next word "is".
s
is a non-empty string consisting of lowercase English letters and spaces.s
by spaces to get individual words.true
if all checks pass; otherwise, return false
.public class Solution {
public boolean isCircularSentence(String s) {
// Split the sentence into words
String[] words = s.split(" ");
// Check for the circular property between words
for (int i = 0; i < words.length; i++) {
int nextIndex = (i + 1) % words.length;
if (words[i].charAt(words[i].length() - 1) != words[nextIndex].charAt(0)) {
return false;
}
}
// If all checks pass, return true
return true;
}
}
n
is the length of the string s
.m
is the number of words in the sentence.s
.This should provide an efficient solution to determining if a sentence is circular based on the problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?