# 题目描述

句子 是由单个空格分隔的一组单词,且不含前导或尾随空格。

例如,"Hello World"、"HELLO"、"hello world hello world" 都是符合要求的句子。 单词 仅 由大写和小写英文字母组成。且大写和小写字母会视作不同字符。

如果句子满足下述全部条件,则认为它是一个 回环句 :

  • 单词的最后一个字符和下一个单词的第一个字符相等。
  • 最后一个单词的最后一个字符和第一个单词的第一个字符相等。

给你一个字符串 sentence ,请你判断它是不是一个回环句。如果是,返回 true ;否则,返回 false

提示:

  • 1 <= sentence.length <= 500
  • sentence 仅由大小写英文字母和空格组成
  • sentence 中的单词由单个空格进行分隔
  • 不含任何前导或尾随空格

# 测试用例

用例1

  • 输入:sentence = "leetcode exercises sound delightful"
  • 输出:true
  • 解释:句子中的单词是 ["leetcode", "exercises", "sound", "delightful"]
  • leetcode 的最后一个字符和 exercises 的第一个字符相等。
  • exercises 的最后一个字符和 sound 的第一个字符相等。
  • sound 的最后一个字符和 delightful 的第一个字符相等。
  • delightful 的最后一个字符和 leetcode 的第一个字符相等。 这个句子是回环句。

用例2

  • 输入:sentence = "Leetcode is cool"
  • 输出:false
  • 解释:句子中的单词是 ["Leetcode", "is", "cool"]
  • Leetcode 的最后一个字符和 is 的第一个字符 不 相等。 这个句子 不 是回环句。

# 代码实现

/**
 * @param {string} sentence
 * @return {boolean}
 */

// 输入

var __readline = require("readline-sync");
__readline.setDefaultOptions({ prompt: "" });
var readline = __readline.prompt;

console.log("请输入sentence: ");
const sentence = readline();

var isCircularSentence = function (sentence) {
  // 大小写不一样
  let first = 0;
  let end = sentence.length - 1;

  // 判断最后一个和第一个
  if (sentence[first] !== sentence[end]) {
    return false;
  }

  while (sentence.indexOf(" ") != -1) {
    // 找到空格位置比较它前后
    let index = sentence.indexOf(" ");
    if (sentence[index - 1] !== sentence[index + 1]) {
      return false;
    }
    // 把当前空格删除
    let temp = sentence.slice(0, index) + sentence.slice(index + 1);
    sentence = temp;
  }

  return true;
};

const res = isCircularSentence(sentence);
console.log("结果为: ", res);

/* 
  请输入sentence:
  leetcode exercises sound delightful
  结果为:  true

  请输入sentence:
  Leetcode is cool
  结果为:  false
*/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51