Skip to content

Instantly share code, notes, and snippets.

@abhisheks-12
Last active December 6, 2021 10:27
Show Gist options
  • Save abhisheks-12/85f4ec518820a3591bacdbad489ae0bf to your computer and use it in GitHub Desktop.
Save abhisheks-12/85f4ec518820a3591bacdbad489ae0bf to your computer and use it in GitHub Desktop.
// function longestPrefixSuffix(s) {
// const n = s.length;
// if (n < 2) {
// return 0;
// }
// const len = 0;
// const i = (n + 1) / 2;
// while (i < n) {
// if (s[i] == s[len]) {
// ++len;
// ++i;
// } else {
// i = i - len + 1;
// len = 0;
// }
// }
// return len;
// }
// fixing bugs
function longestPrefixSuffix(s) {
const n = s.length;
if (n < 2) {
return 0;
}
let len = 0;
let i = (n + 1) / 2;
while (i < n) {
if (s[i] == s[len]) {
++len;
++i;
} else {
i = i - len + 1;
len = 0;
}
}
return len;
}
console.log(longestPrefixSuffix('ABCDEFGABCD'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment