精華區beta Marginalman 關於我們 聯絡資訊
https://leetcode.com/problems/circular-sentence 2490. Circular Sentence 如果句子中的單字 前一個單字的最後一個字元 等於 下一個單字的第一個字元 以及 最後一個單字的最後一個字元 等於 第一個單字的第一個字元 則該句子是循環語句 大小寫字母視為不同 Example 1: Input: sentence = "leetcode exercises sound delightful" Output: true Example 2: Input: sentence = "eetcode" Output: true Example 3: Input: sentence = "Leetcode is cool" Output: false Constraints: 1 <= sentence.length <= 500 sentence 只包含大小寫字母跟空格 sentence 的單字由一個空格分隔 沒有起始空格或結尾空格 思路1: 用 split 把句子分成單字list之後 判斷相鄰單字間頭尾是否相同 Python Code: class Solution: def isCircularSentence(self, sentence: str) -> bool: s = sentence.split() for i in range(-1, len(s)-1): if s[i][-1] != s[i+1][0]: return False return True 思路2: 先判斷句子頭尾是否相同 循環一遍句子 當遇到空格時再判斷 Python Code: class Solution: def isCircularSentence(self, sentence: str) -> bool: if sentence[0] != sentence[-1]: return False for i in range(len(sentence)): if sentence[i] == ' ' and sentence[i-1] != sentence[i+1]: return False return True 又是對大師們來說太簡單的一天 沒人發 :( 補個JavaScript的寫法 不過跟思路2一樣就是了 JavaScript Code: /** * @param {string} sentence * @return {boolean} */ var isCircularSentence = function(sentence) { if (sentence[0] !== sentence[sentence.length - 1]) { return false; } for (var i = 0; i < sentence.length - 1; i++) { if (sentence[i] === ' ' && sentence[i - 1] !== sentence[i + 1]) { return false; } } return true; }; -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.45.55.73 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1730584830.A.C50.html