Leetcode 2490. Circular Sentence
Given a sentence that consists of only lowercase English letters and spaces, we say that the sentence is circular if the last character of a word is the same as the first character of the next word. Your task is to determine whether a given sentence is circular.
For example, the sentence "leetcode exercises sound delightful"
is circular because the last character of each word matches the first character of the next word:
leetcode
ends with ‘e’ and exercises
starts with ‘e’exercises
ends with ‘s’ and sound
starts with ‘s’sound
ends with ‘d’ and delightful
starts with ‘d’Write a function to determine if the given sentence is circular.
To solve this problem, we can follow these steps:
Here is the C++ code to implement this logic:
#include <iostream>
#include <vector>
#include <sstream>
bool isCircularSentence(const std::string& sentence) {
std::vector<std::string> words;
std::stringstream ss(sentence);
std::string word;
// Split the sentence into words
while (ss >> word) {
words.push_back(word);
}
int n = words.size();
for (int i = 0; i < n; ++i) {
char lastChar = words[i].back();
char firstCharNext = words[(i + 1) % n].front();
if (lastChar != firstCharNext) {
return false;
}
}
return true;
}
int main() {
std::string sentence = "leetcode exercises sound delightful";
if (isCircularSentence(sentence)) {
std::cout << "The sentence is circular." << std::endl;
} else {
std::cout << "The sentence is not circular." << std::endl;
}
return 0;
}
Thus, the overall time complexity of the solution is O(n + m). Since m (number of words) is typically much smaller than n (number of characters in the sentence), the dominant term is O(n).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?