Try   HackMD

459.Repeated Substring Pattern

tags: Easy String

459. Repeated Substring Pattern

題目描述

Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.

範例

Example 1:

Input: s = "abab"
Output: true
Explanation: It is the substring "ab" twice.

Example 2:

Input: s = "aba"
Output: false

Example 3:

Input: s = "abcabcabcabc"
Output: true
Explanation: It is the substring "abc" four times or the substring "abcabc" twice.

Constraints:

  • 1 <= s.length <= 104
  • s consists of lowercase English letters.

解答

Javascript

function repeatedSubstringPattern(s) { const len = s.length >> 1; let subString = ''; for (let i = 0; i < len; i++) { subString += s[i]; let tempString = subString; while (tempString.length < s.length) { tempString += subString; } if (tempString === s) return true; } return false; }
function repeatedSubstringPattern2(s) { return s.repeat(2).slice(1, -1).includes(s); }

下面一行的解是我弟教我的,跟鬼一樣。
MarsgoatAug 21, 2023

Reference

回到題目列表