• JavaScript算法41- 回环句(leetCode:6253easy)周赛


    6253. 回环句

    一、题目

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

    • 例如,"Hello World""HELLO""hello world hello world" 都是符合要求的句子。
      单词 由大写和小写英文字母组成。且大写和小写字母会视作不同字符。
      如果句子满足下述全部条件,则认为它是一个 回环句
    • 单词的最后一个字符和下一个单词的第一个字符相等。
    • 最后一个单词的最后一个字符和第一个单词的第一个字符相等。

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

    示例 :

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

    提示:

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

    二、题解

    • 利用 reduce() 比较前一个单词的尾字符和后一个单词的首字符
    /**
     * @param {string} sentence
     * @return {boolean}
     */
     var isCircularSentence = function(sentence) {
        let wordList = sentence.split(' ');
        let isCircular = true;
        let lastWordChar = wordList.reduce((preLastChar,curWord,curIndex) => {
            // 比较当前word的第一个字符和前一个word的最后一个字符是否相等
            if((preLastChar !== curWord.charAt(0) && curIndex)) isCircular = false;
            // 返回当前word的最后一个字符
            return curWord.charAt(curWord.length-1);
        },'')
        if(wordList[0].charAt(0) !== lastWordChar)return false;
        return isCircular;
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    在这里插入图片描述

    三、扩展 reduce

    累计 reduce():依次处理数组的每个成员,最终累计成一个值。
    reduce((previousValue, currentValue, currentIndex, array) => { /* … */ }, initialValue)

    // 示例1:求和
    const arr = [3,4,4,5,4,6,5,7];
    const sum = arr.reduce((pre, cur) => {return pre+cur})
    
    //示例2:数组去重
    const newArr = arr.reduce((pre, cur) => {
    	if(!pre.includes(cur)){
    		return pre.concat(cur);
    	}
    	return pre;
    }, [])
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
  • 相关阅读:
    ADFS和NingDS两种统一身份认证,哪种方案更适合现代中小企业?(下)
    面向对象编程原则(02)——单一职责原则
    屏幕距离识别加语音提醒
    Allegro走线自动关闭其它飞线操作指导
    Python tkinter -- 第11章滚动条
    力扣第435题 无重叠区间 c++ 贪心思维
    【Vue项目复习笔记】tabControl组件的吸顶效果
    Flask像Jenkins一样构建自动化测试任务
    Controller 层编码规范
    FreeRTOS移植
  • 原文地址:https://blog.csdn.net/Y_soybean_milk/article/details/128174048