LeetCode 2490. 回环句

​​​​​​​2490. 回环句

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

  • 例如,"Hello World""HELLO""hello world hello world" 都是符合要求的句子。

单词  由大写和小写英文字母组成。且大写和小写字母会视作不同字符。

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

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

例如,"leetcode exercises sound delightful""eetcode""leetcode eats soul" 都是回环句。然而,"Leetcode is cool""happy Leetcode""Leetcode" 和 "I like Leetcode" 都  是回环句。

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

示例 1:

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

示例 2:

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

示例 3:

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

提示:

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

提示 1

Check the character before the empty space and the character after the empty space.


提示 2

Check the first character and the last character of the sentence.

解法:回环

相似题型:

LeetCode 1652. 拆炸弹-CSDN博客

LeetCode 2515. 到目标字符串的最短距离-CSDN博客

class Solution {
    public boolean isCircularSentence(String sentence) {
        String[] str = sentence.split(" ");
        int n = str.length;
        for (int i = 0; i < n; i++) {
            // 单词的最后一个字符
            Character l = str[i].charAt(str[i].length() - 1);
            // 下一个单词的第一个字符
            Character r = str[(i + 1) % n].charAt(0);
            if (!l.equals(r)) {
                return false;
            }
        }
        return true;
    }
}

复杂度分析 

  • 时间复杂度:O(n),n 是 字符串sentence 的单词个数。
  • 空间复杂度:O(n),n 是 字符串sentence 的单词个数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值