Sponsored
Sponsored
This method involves splitting the sentence into words and verifying the circular property by manually comparing the last character of one word with the first character of the next word, including checking the condition from the last word to the first word.
Time complexity: O(n), where n is the length of the sentence.
Space complexity: O(1), as no additional data structures are used.
1
In this JavaScript solution, the program splits the sentence, verifies each word with its successor, and ensures the sentence as a whole forms a loop by comparing first and last word characters.
This approach uses two pointers to traverse through the sentence. One pointer identifies word endings, the other starts at the first character of new words. This methodology avoids splitting the sentence into words explicitly.
Time complexity: O(n), due to the traversal of the sentence.
Space complexity: O(1), as it involves no auxiliary storage.
1public class CircularSentence {
2 public static boolean isCircularSentence(String sentence) {
3 int n = sentence.length();
4 char startChar = sentence.charAt(0);
5 char lastChar = sentence.charAt(n - 1);
6
7 if (startChar != lastChar) return false;
8
9 for (int i = 1; i < n; i++) {
10 if (sentence.charAt(i) == ' ' && sentence.charAt(i - 1) != sentence.charAt(i + 1)) {
11 return false;
12 }
13 }
14
15 return true;
16 }
17
18 public static void main(String[] args) {
19 String sentence = "leetcode exercises sound delightful";
20 System.out.println(isCircularSentence(sentence));
21 }
22}
This Java solution employs a simple index-based approach that works effectively with a single loop to establish the circular condition without parsing individual words into a separate data structure.