LeetCode 2490: Circular Sentence
Problem Description
Explanation:
To determine if a sentence is circular, we need to check if the last character of each word is equal to the first character of the next word, and if the last character of the last word is equal to the first character of the first word.
- Split the input sentence into individual words.
- Iterate through the words and check if the last character of each word matches the first character of the next word.
- Finally, check if the last character of the last word matches the first character of the first word.
- If all conditions are met, the sentence is circular.
Time Complexity: O(n), where n is the number of characters in the input sentence. Space Complexity: O(n), where n is the number of characters in the input sentence.
:
Solutions
class Solution {
public boolean isCircular(String sentence) {
String[] words = sentence.split(" ");
for (int i = 0; i < words.length - 1; i++) {
if (words[i].charAt(words[i].length() - 1) != words[i + 1].charAt(0)) {
return false;
}
}
return words[words.length - 1].charAt(words[words.length - 1].length() - 1) == words[0].charAt(0);
}
}
Loading editor...