考虑用滑动窗口
function findSequence(str) { // 滑动窗口 // 1.分离成数组 const arr = str.split(','); const n = arr.length; if (n < 2) return str; // 2.左右指针指向第一个和第二个元素 let left = 0; let right = 1; const res = []; // 5.条件是right<str.length while (right < n) { const current = arr[right]; // 3.若右指针所指是上一个加一 right++ if (current - '0' === arr[right - 1] - '0' + 1) { right++; } else { // 若arr[left] === arr[right - 1]则+arr[left] let temp = ''; if (left === right - 1) { temp += arr[left] } else { temp += arr[left] + '~' + arr[right - 1] } res.push(temp); // 4.否则left = right right = left+1 left = right; right = left + 1; } } // 6.最后判断若left在length-1处则push最后一个字符 // 否则push从left到最后一个的字符 if (left === n - 1) { res.push(arr[left]) } else { let temp = arr[left] + '~' + arr[n - 1]; res.push(temp); } return res.join(',') }组件之间传值传送门
