Files
wehub-resource-sync dde272c4b8
i18n - Build Validation / Validate i18n Builds (24) (push) Has been cancelled
CI - Node.js / Lint (24) (push) Has been cancelled
CI - Node.js / Build (24) (push) Has been cancelled
CI - Node.js / Test (24) (push) Has been cancelled
CI - Node.js / Test - Upcoming Changes (24) (push) Has been cancelled
CI - Node.js / Test - i18n (italian, 24) (push) Has been cancelled
CI - Node.js / Test - i18n (portuguese, 24) (push) Has been cancelled
CD - Docker - GHCR Images / Build and Push Images (push) Has been cancelled
chore: import upstream snapshot with attribution
2026-07-13 11:55:53 +08:00

75 lines
1.6 KiB
Markdown

---
id: 69cfca90e8a0a6d4d6871c54
title: "Challenge 270: Longest Common Substring"
challengeType: 28
dashedName: challenge-270
---
# --description--
Given a string, return the longest substring that appears more than once.
- The substrings can overlap.
# --hints--
`getLongestSubstring("abracadabra")` should return `"abra"`.
```js
assert.equal(getLongestSubstring("abracadabra"), "abra");
```
`getLongestSubstring("hello world hello")` should return `"hello"`.
```js
assert.equal(getLongestSubstring("hello world hello"), "hello");
```
`getLongestSubstring("mississippi")` should return `"issi"`.
```js
assert.equal(getLongestSubstring("mississippi"), "issi");
```
`getLongestSubstring("ha ha ha ha ha ha ha")` should return `"ha ha ha ha ha ha"`.
```js
assert.equal(getLongestSubstring("ha ha ha ha ha ha ha"), "ha ha ha ha ha ha");
```
`getLongestSubstring("the quick brown fox jumped over the lazy dog that the quick brown fox jumped over")` should return `"the quick brown fox jumped over"`.
```js
assert.equal(getLongestSubstring("the quick brown fox jumped over the lazy dog that the quick brown fox jumped over"), "the quick brown fox jumped over");
```
# --seed--
## --seed-contents--
```js
function getLongestSubstring(str) {
return str;
}
```
# --solutions--
```js
function getLongestSubstring(str) {
let longest = '';
for (let len = str.length - 1; len >= 1; len--) {
for (let i = 0; i <= str.length - len; i++) {
const sub = str.slice(i, i + len);
if (str.indexOf(sub) !== str.lastIndexOf(sub)) {
return sub;
}
}
}
return longest;
}
```