2490. 回环句

2490. 回环句

2490. 回环句_第1张图片


js代码:

/**
 * @param {string} sentence
 * @return {boolean}
 */
var isCircularSentence = function(sentence) {
    const n = sentence.length;
    if (sentence[n - 1] !== sentence[0]) {
        return false;
    }
    for (let i = 0; i < n; i++) {
        if (sentence[i] === ' ' && sentence[i + 1] !== sentence[i - 1]) {
            return false;
        }
    }
    return true;
};
var isCircularSentence = function (sentence) {
    const list = sentence.split(' ');
    const len = list.length;
    for (let i = 0; i < len; i++) {
        if (i == len - 1) {
            if (lastValue(list[len-1]) !== firstValue(list[0])) {
                return false;
            }
        } else {
            if (lastValue(list[i]) !== firstValue(list[i + 1])) {
                return false;
            }
        }
    }
    return true
};
var lastValue = (value) => {
    return value[value.length - 1];
}
var firstValue = (value) => {
    return value[0];
}
/**
 * @param {string} sentence
 * @return {boolean}
 */
const isCircularSentence = (sentence) => {
  const words = sentence.split(" ");
  
  return words.every((word, i, arr) => {   // 这有点不理解了...
    const nextIndex = (i + 1) % arr.length;
    return word[word.length - 1] === arr[nextIndex][0];
  });
};

你可能感兴趣的:(LeetCode刷题,算法)