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#include <sstream>
using namespace std;
bool isCircularSentence(string sentence) {
istringstream stream(sentence);
string word, prevWord;
stream >> word;
char firstChar = word.front();
char prevLastChar = word.back();
prevWord = word;
while (stream >> word) {
if (prevLastChar != word.front()) {
return false;
}
prevLastChar = word.back();
}
return prevLastChar == firstChar;
}
int main() {
string sentence = "leetcode exercises sound delightful";
cout << (isCircularSentence(sentence) ? "true" : "false") << endl;
return 0;
}
The approach uses an input string stream to access words individually and checks their circular property as it progresses. Finally, it validates the initial and final 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.
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.