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 <iostream>
2#include <string>
3using namespace std;
4
5bool isCircularSentence(string sentence) {
6 int n = sentence.size();
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
18 return true;
19}
20
21int main() {
22 string sentence = "leetcode exercises sound delightful";
23 cout << (isCircularSentence(sentence) ? "true" : "false") << endl;
24 return 0;
25}
This C++ program iterates linearly, checking adjacent word characters whenever a space acts as a boundary. The first and last characters are also checked to validate circularity.