[LeetCode] Circular Sentence

2490. Circular Sentence

A sentence is a list of words that are separated by a single space with no leading or trailing spaces.

  • For example, “Hello World”, “HELLO”, “hello world hello world” are all sentences.

Words consist of only uppercase and lowercase English letters. Uppercase and lowercase English letters are considered different.

A sentence is circular if:

  • The last character of a word is equal to the first character of the next word.
  • The last character of the last word is equal to the first character of the first word.

For example, “leetcode exercises sound delightful”, “eetcode”, “leetcode eats soul” are all circular sentences. However, “Leetcode is cool”, “happy Leetcode”, “Leetcode” and “I like Leetcode” are not circular sentences.

Given a string sentence, return true if it is circular. Otherwise, return false.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
bool isCircularSentence(string A) {
for(int i = 0; i < A.length(); i++) {
if(i == A.length() - 1) {
if(A[0] != A[i]) return false;
}
else if(A[i] == ' ') {
if(i + 1 == A.length()) return false;
if(A[i-1] != A[i+1]) return false;
}
}
return true;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/12/04/PS/LeetCode/circular-sentence/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.