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
This solution iterates through the given sentence, considering spaces as word boundaries. It checks every word's last character against the next one's first character and finally checks the sentence's first and last character.
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.
1#include <stdio.h>
2#include <stdbool.h>
3#include <string.h>
4
5bool isCircularSentence(char* sentence) {
6 int n = strlen(sentence);
7 char startChar = sentence[0];
8 char lastChar = sentence[n-1];
9
10 if (startChar != lastChar) return false;
11
12 for (int i = 1; i < n; i++) {
13 if (sentence[i] == ' ' && sentence[i-1] != sentence[i+1]) {
14 return false;
15 }
16 }
17 return true;
18}
19
20int main() {
21 char* sentence = "leetcode exercises sound delightful";
22 if (isCircularSentence(sentence)) {
23 printf("true\n");
24 } else {
25 printf("false\n");
26 }
27 return 0;
28}
This C code processes the string with a single for-loop, using indexes to track word boundaries and assessing the circular criteria directly.