-
Notifications
You must be signed in to change notification settings - Fork 3.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
第 110 题:编程题,请写一个函数,完成以下功能 #201
Comments
@lonycc 朋友,你明显理解错了,这道题的意思是:如果连续数字的话,就取连续的第一个数和最后一个数,中间用~隔开。如果不连续就用,隔开。 |
function simplifyStr(str) {
let pre = void 0;
return `${str},`.replace(/ /, '').replace(/\d+,(?=(\d+|\B))/g, (current, next) => {
const _current = +current.split(',')[0]
pre = pre === undefined ? +_current : pre
const res = +next === _current + 1 ? (
pre + 1 === _current ? '' : _current
) : (
pre + 1 === _current ? `~${_current}${next ? ',' : ''}` : current
)
pre = _current
return res
})
} |
想看各位大佬的最佳操作,我就简陋的写了一下。const nums1 = [1, 2, 3, 5, 7, 8, 10];
function simplifyStr(num) {
var result = [];
var temp = num[0]
num.forEach((value, index) => {
if (value + 1 !== num[index + 1]) {
if (temp !== value) {
result.push(`${temp}~${value}`)
} else {
result.push(`${value}`)
}
temp = num[index + 1]
}
})
return result;
}
console.log(simplifyStr(nums1).join(',')) |
我也来参与一下~
|
@lhyt 大佬,你的方法运行的结果,最后会多个逗号。。 |
function transformStr(str) {
const arr = str.split(',').map(x => parseInt(x));
let result = [arr[0], arr[1]], i = 1, isContinuous = false;
arr.forEach((value, index) => {
if (index > 1) {
if (value === result[i] + 1 && result[i] - result[i-1] === 1) {
result[i] = value;
isContinuous = true;
} else {
isContinuous = false;
result.push(value);
i++;
}
if(isContinuous || result[i] - result[i-1] === 1)result[i] = `~${result[i]}`;
}
})
return result.toString().replace(/,(?=~)/g, '');
}
const str = '1,2,3,5,7,8,10,11';
console.log(transformStr(str)); |
哈哈,还在疑惑呢,题目是啥意思,原来是markdown中两个~构成了删除线,要用\~来写~呢 |
function getSerial(src) {
let srcArray = src.split(',').map(num => +num)
if (srcArray.length === 0) return ''
let result = '' + srcArray[0]
let serialCount = 0
for (let i = 1; i < srcArray.length; i++) {
if (srcArray[i] !== srcArray[i - 1] + 1) {
result += (serialCount > 0 ? '~' + srcArray[i - 1] : '') + ',' + srcArray[i]
serialCount = 0
} else {
serialCount++
if (i === srcArray.length - 1) {
result += '~' + srcArray[i]
}
}
}
return result
} |
@whyour 你这个方法在最后两位是连续的时候,结果不对。传入 '1,2,3,5,7,8' ,输出的是 1~3,5,7,8 |
const str = '1,2,3,5,7,8,10;
const transformStr = ( str ) => '1~3,5,7~8,10'; 😈😈😈😈😈😈😈 |
public static void main(String[] args) {
|
function classification(data){ |
let str = '1,2,3,5,7,8,10,12,13,14,100,101,102';
const strGroup = (arr) =>
arr.reduce((acc, item) => {
let lastArr = acc.slice().pop() || []
let lastNum = lastArr.slice().pop()
if (lastNum == item - 1 || (lastNum && lastNum.match(/(\w*)(\w)/g)[1] == item - 1)) {
lastArr.pop()
let curStr = /\~.*/.test(lastNum)
? lastNum.replace(/\~.*/, `~${item}`)
: `${lastNum}~${item}`
lastArr.push(curStr)
} else {
acc.push([item])
}
return acc
}, []).join(',')
strGroup(str.split(',')) // 1~3,5,7~8,10,12~14,100~102 灵感来源 67题 ,来自 @benzhemin的求连续版本 |
这种好像用bitmap也很好处理 |
const transformString = function(string) {
let first = null;
let tempArr = []
let arr = string.split(',').map(item => Number(item))
arr.forEach((current, index) => {
if(index === 0) {
first = current
} else {
let prev = arr[index - 1]
if(current !== prev + 1) {
first === prev ? tempArr.push(`${first}`) : tempArr.push(`${first}~${prev}`);
first = current
}
arr.length - 1 === index && (first === current ? tempArr.push(`${first}`) : tempArr.push(`${first}~${current}`))
}
})
return tempArr.join(',')
}
console.log(transformString('1,2,3,5,7,8,10,12,13,14,100,101,102')) |
let str = "1, 2, 3, 5, 7, 8, 10";
function computed(str) {
let arr = str.split(",");
let pos = 0, index = 0, flag = true;
for (let i = 0; i <= arr.length; i++) {
if (Number(arr[i - 1]) + 1 == arr[i]) {
if (flag) {
pos = i;
}
index++;
flag = false;
} else {
if (!flag) {
arr.splice(pos, index - 1, "~");
}
flag = true;
i = i - index;
index = 0;
}
}
return arr.join(",").replace(/\,~\,/g, "~");
}
console.log(computed(str)); |
const numRange = function (arr) {
arr = arr.split(',')
let result = []
let map = {}
let count = 0
for (let i = 0; i < arr.length; i++) {
if (i === 0) {
map[count] = [arr[i]]
continue
}
if (+arr[i] - 1 === +arr[i - 1]) {
map[count].push(arr[i])
} else {
count++
map[count] = [arr[i]]
}
}
for (const key in map) {
if (map.hasOwnProperty(key)) {
const range = map[key]
if (range.length > 1) {
result[key] = [range[0], range[range.length - 1]].join('~')
} else {
result[key] = range.join('')
}
}
}
return result.join(',')
}
numRange('1,3,4,5,6,8,9,20') // => "1,3~6,8~9,20" |
function f(params) {
const arr = params.split(',')
const res = []
let first = arr[0]
let next = 0
for (let i = 0; i < arr.length; i++) {
if (+arr[i]+1 === +arr[i+1]) {
next = arr[i + 1]
} else {
if (next !== 0) {
res.push(`${first}~${next}`)
} else {
res.push(arr[i])
}
first = arr[i + 1]
next = 0
}
}
return res.join(',')
} |
|
function reSort(arr) {
var current = 0;
var len = 0;
for(let i=1; i<arr.length; i++) {
if(arr[i] - arr[i-1] !== 1) {
if(!len) continue;
arr.splice(current , len - 1, '~');
i = i - len + 2;
current = 0;
len = 0;
}else{
current = current || i;
len++;
if(i === arr.length - 1) {
arr.splice(current , len - 1, '~');
}
}
}
return arr.join(',').replace(/,~,/g, '~');
}
var str = "1,2,3,4,6,7,9,10,11";
console.log(reSort(str.split(','))); 求大佬们点评 |
测试通过 function transformStr(str) {
let arr = str.split(',')
let i = 0
let ret = []
for (let j = 1; j <= arr.length; j++) {
if (arr[j] - arr[j - 1] !== 1) {
ret.push(j - i === 1 ? arr[i] : `${arr[i]}~${arr[j - 1]}`)
i = j
}
}
return ret.join(',')
} |
一行代码(嘿嘿)修改了重名变量,方便理解 function transArr(str) {
return str.split(",").map((item, key, arr) => (arr[key + 1] != +item + 1 || key === 0 || arr[key - 1] != item - 1) ? item == +arr[key - 1] + 1 ? `,${item}` : item : ",").toString().replace(/(,)\1+/g, '~')
} |
|
const nums1 = [ 1, 2, 3, 4, 5, 7, 8, 10, 13, 22, 122 ]; |
|
} |
|
export function intervalNum (list) {
let result = [] // 分隔连续数字的区间标记
let prewVal = null
let initVal = null
if (list === '') {
return ''
}
list = list.split(',')
// mark记录非连续数字的第一个值
list.forEach((item, index) => {
if (prewVal && Number(prewVal) === (Number(item) - 1)) {
result.push(initVal + '->' + index + '~' + item)
// (marks[marks.length - 1] - mark[marks.length - 2] === 1) ? marks.splice(marks.length - 2, 1) : () => {}
if (result[result.length - 1].indexOf(initVal + '->') > -1) {
result.splice(result.length - 2, 1)
}
} else if (!prewVal) {
initVal = item
result.push(item + '->')
} else {
initVal = item
result.push(item + '->')
}
prewVal = item
})
result = result.map(item => {
return item.split('->')[0] + (item.split('->')[1].split('~ ')[1] ? item.split('->')[1].split('~ ')[1] : '')
})
return result.join(',')
} |
var continueNum=function(str){
var numarr=str.split(",");
var result=[];var queue=[];
for(let i=0;i<numarr.length;i++)
{
if((numarr[i+1]-numarr[i])==1)
{
queue.push(numarr[i]);
}
else
{
queue.push(numarr[i]);
if(queue.length!=1)
{result.push(queue[0]+"~"+queue[queue.length-1]);queue.length=0}
else
{result.push(queue[0]);queue.length=0}
}
}
return result.join(",");
} |
function simplifyStr(str) {
if (!str || str.length === 1) return
let lockFlag = false;
let arr = str.split(',')
let startItem = arr[0],
endItem = arr[1],
res = []
for (let i = 1; i < arr.length; i++) {
if ((arr[i] - arr[i - 1]) !== 1) {
lockFlag = true;
endItem = arr[i - 1];
startItem === endItem && res.push(`${endItem}`);
startItem !== endItem && res.push(`${startItem}~${endItem}`);
startItem = arr[i];
if (i === arr.length - 1) {
res.push(`${arr[i]}`)
}
} else {
endItem = arr[i]
}
}
if (!lockFlag) {
res.push(`${startItem}~${endItem}`)
}
return res.join(',')
} |
function test(str) {
return str.split(',').reduce((acc, cur, curIndex, arr) => {
if (!curIndex) return cur
const pre = arr[curIndex - 1]
if (+pre === +cur - 1) {
const reg = new RegExp(`~${pre}$`)
acc = reg.test(acc) ? acc.replace(reg, `~${cur}`) : (acc + `~${cur}`)
} else {
acc += `,${cur}`
}
return acc
}, '')
}
test('1,2,3,5,7,8,10') |
function simplifyStr(str) {
let arr = str.split(',').map(v => +v)
let len = arr.length
if (!len) {
return ''
}
let list = []
let pre = arr[0]
for (let i = 1; i < len; i++) {
if (arr[i] !== arr[i - 1] + 1) {
list.push(pre === arr[i - 1] ? pre : `${pre}~${arr[i - 1]}`)
pre = arr[i]
}
}
list.push(pre === arr[len - 1] ? pre : `${pre}~${arr[len - 1]}`)
return list.join(',')
} |
参与一下 var str = '1,2,3,5,7,8,9,12'
function format(str) {
let arr = str.split(',').map((_) => _ - 0) // [1, 2, 3, 5,7,8,10]
const result = []
for (let i = 0, len = arr.length - 1; i < len; i++) {
if (arr[i + 1] - arr[i] === 1) {
const theLast = result[result.length - 1]
if (!(theLast === '~')) {
result.push(arr[i])
result.push('~')
}
} else {
result.push(arr[i])
}
}
result.push(arr.pop())
return result.join(',').replace(/,~,/g, '~')
}
console.log(format(str)) |
const arr = [1, 2, 3, 5, 7, 8, 10]
const solution = (arr) => {
let res = []
let start = arr[0]
let end = arr[0]
for (let i = 0; i < arr.length; i++) {
if (arr[i] + 1 === arr[i + 1]) {
end = arr[i + 1]
} else {
res.push(start === end ? start : `${start}~${end}`)
start = arr[i + 1]
end = arr[i + 1]
}
}
return res
}
console.log(solution(arr)) |
const getArea = (str) => {
const arr = str.split(',')
let res = ''
let start = arr[0], end = ''
for(let i=1; i<arr.length; i++){
if(arr[i] - arr[i-1] == 1){
end = arr[i]
}else {
let t = start + (end ? '~' + end : '')
res += res ? ',' + t : t
start = arr[i]
end = ''
}
}
let t = start + (end ? '~' + end : '')
res += res ? ',' + t : t
return res
}
getArea('1, 2, 3, 5, 7, 8, 10') |
const convert = function (arr) {
const ans = [];
const n = arr.length;
for (let i = 0; i < n; i++) {
const start = arr[i];
let end = arr[i];
while (i + 1 < n && arr[i + 1] === end + 1) {
end = arr[i + 1];
i++;
}
ans.push(end === start ? start : `${start}~${end}`);
}
return ans;
};
console.log(convert([1, 2, 3, 5, 7, 8, 10])); // ['1~3', 5, '7~8', 10] |
// 双指针/滑动窗口
const fn = str => {
let ary = str.split(','),
res = [],
i = 0,
j = 0
let length = ary.length
while (j < length) {
if (ary[j + 1] - ary[j] !== 1) {
if (j - i > 0) {
res.push(`${ary[i]}~${ary[j]}`)
} else {
res.push(ary[j])
}
i = j + 1
}
j++
}
return res.toString()
} |
写完之后看看 大佬的 const magic = (arr) => {
let resultArr = [];
let cacheArr = [];
for (let index = 0; index < arr.length; index++) {
const element = arr[index];
if (index === 0) {
cacheArr.push(element);
} else {
const qqLastItem = cacheArr[cacheArr.length - 1];
if (element - 1 === qqLastItem) {
cacheArr.push(element);
} else {
resultArr.push(cacheArr);
cacheArr = [];
cacheArr.push(element);
}
}
}
return resultArr.reduce((acc, cur) => {
if (cur.length > 1) {
acc.push(`${cur[0]}~${cur[cur.length - 1]}`);
} else {
acc.push(cur[0]);
}
return acc;
}, []);
};
console.log(magic([1, 2, 3, 5, 7, 8, 10])); // [ '1~3', 5, '7~8' ] |
图片凉了,看不到题目了 |
/**
* 输入 1,2,3,5,7,8,10, 输出 1~3,5,7~8,10
* 如果连续数字的话,就取连续的第一个数和最后一个数,中间用 "~" 隔开。如果不连续就用 "," 隔开。
*/
const str = '1,2,3,5,7,8,10,12,13,14,15,20';
const result = str.split(',').map(Number).reduce((pre, cur, index, arr) => {
if (index === 0) {
pre = `${cur}`;
return pre;
}
if (arr[index - 1] === cur - 1) {
pre += `~${cur}`;
} else {
pre +=`,${cur}`
}
return pre;
}, '').replace(/(~\d+)+~/g, '~');
console.log(result); |
function format(str) {
const arr = str.split(',')
const result = []
let start
for (let i = 0; i < arr.length; i++) {
start = arr[i]
while (arr[i + 1] - arr[i] === 1 && i + 1 < arr.length) {
i++
}
if (arr[i] !== start) {
result.push(`${start}~${arr[i]}`)
} else {
result.push(start)
}
}
return result.join(',')
}
console.log(format('1,2,3,5,7,8,10')); |
const str = '1, 2, 3, 5, 7, 8, 10';
function parseNum(str) {
const _arr = str.split(',');
const _result = [];
let _temp = [];
while (_arr.length > 0) {
const last = +_arr.shift();
if (_temp.length === 0) {
_temp.push(last);
continue;
}
if (last - _temp[_temp.length - 1] < 2) {
_temp.push(last);
} else {
_result.push(_temp.length === 1 ? _temp[0] : `${_temp[0]}~${_temp[_temp.length - 1]}`);
_temp = [last];
}
}
if (_temp.length > 0) _result.push(_temp.length === 1 ? _temp[0] : `${_temp[0]}~${_temp[_temp.length - 1]}`);
return _result.join(',');
}
console.log(parseNum(str)); |
function convert(str = '') {
const arr = str.split(',')
let i = 0, j = i + 1
const res = []
let resStr = [arr[0]]
while(true) {
if(i === arr.length) break
let cur = arr[i]
let next = arr[j]
if(next - cur === 1) {
resStr.push(next)
} else {
resStr.length === 1 ? res.push(resStr[0].trim()) : res.push(`${resStr[0].trim()}~${resStr[resStr.length - 1].trim()}`)
resStr = [arr[j]]
}
i = j
j ++
}
return res.join(',')
} |
题意为连续数字用~连接然后成为一部分,非连续数字自成一部分 当r-l>=1,说明左右两端都有数字,需加~ function solution(str) {
let arr = str.split(', ');
let l = 0, r = 0, n = arr.length;
let res = []
while (l < n) {
const diff = parseInt(arr[r + 1]) - parseInt(arr[r])
const interval = r - l
if (diff === 1) {
r++
} else if (interval >= 1) {
res.push(`${arr[l]}~${arr[r++]}`)
l = r
} else {
res.push(arr[l++])
r++
}
}
return res.join(',')
}
// let str = '1, 2, 3, 5, 7, 8, 10';
let str = '1, 2, 3, 4, 7, 8, 10, 13, 15';
console.log(solution(str)) |
|
|
個人解法: function output(str) {
const nums = str.split(',').map(e => +e);
let result = '', continuous = [];
for(let i = 0; i < nums.length; i++) {
if (nums[i] + 1 === nums[i + 1]) {
continuous.push(nums[i]);
} else if (nums[i] + 1 !== nums[i + 1] && continuous.length > 0) {
continuous.push(nums[i]);
result += `,${continuous[0]}~${continuous[continuous.length - 1]}`
continuous = [];
} else {
result += `,${nums[i]}`
}
}
return result.substring(1);
}
console.log(output('1,2,3,5,7,8,10')); |
这是一封自动回复邮件。您好,你的邮件我已收到,会尽快给您回复,祝您生活愉快!
|
|
function transform(arr) {
arr = arr.split(',').map(i => +i)
let result = []
let index = 0
while(arr.length) {
let target = arr.shift()
result[index] ? result[index].push(target) : (result[index] = [target])
if (target !== arr[0] - 1) index++
}
result = result.map(item => {
if (item.length >= 2) {
item = [item[0], '~', item[item.length - 1]]
}
item = item.join('')
return item
})
return result.join(',')
} |
这是一封自动回复邮件。您好,你的邮件我已收到,会尽快给您回复,祝您生活愉快!
|
|
这是一封自动回复邮件。您好,你的邮件我已收到,会尽快给您回复,祝您生活愉快!
|
const collectContinuous = (rawString) => {
const numList = rawString.split(',').map((elem) => Number(elem));
const recordArr = [];
let start, prev;
const end = numList.length - 1;
for (let i = 0; i <= end; i++) {
start = prev = numList[i];
for (let cursor = i+1; cursor<= end && prev+1 === numList[cursor]; cursor++) {
prev = numList[cursor];
i = cursor;
}
start === prev ? recordArr.push(`${start}`) : recordArr.push(`${start}~${prev}`);
}
console.log(recordArr.join(','))
};
const input = "1,2,3,5,7,8,10";
collectContinuous(input);
|
这是一封自动回复邮件。您好,你的邮件我已收到,会尽快给您回复,祝您生活愉快!
|
const arr = [1, 2, 3, 5, 7, 8, 10];
let i = 0, j = i + 1, res = [];
while (i < arr.length) {
if (arr[j] - arr[j - 1] === 1) {
j++;
} else {
if (j - i > 1) res.push(`${arr[i]}-${arr[j - 1]}`);
else res.push(arr[i]);
i = j;
j = i + 1;
}
}
console.log(res) |
function foo(input) {
const ary = input.split(',').map(Number);
let temp = ary[0];
const result = ary.reduce((acc, cur, index, theAry) => {
if (cur + 1 === theAry[index + 1]) return acc;
acc.push(cur === temp ? cur : `${temp}~${cur}`);
temp = theAry[index + 1];
return acc;
}, []);
return result.toString();
}
console.log(foo('1,2,3,5,7,8,10')); |
function groupNums(nums) {
const len = nums.length;
const SEPARATOR = '~';
const result = [];
if(!len) {
return '';
}
nums.sort((a, b) => a - b);
let from = nums[0];
for(let i = 1; i < nums.length; i++) {
if(nums[i] - nums[i - 1] !== 1) {
result.push(from === nums[i - 1] ? from : `${from}${SEPARATOR}${nums[i - 1]}`);
from = nums[i];
}
}
result.push(from === nums[len - 1] ? from : `${from}${SEPARATOR}${nums[len - 1]}`);
return result.join(',');
}
console.log(groupNums([1, 2, 3, 5, 7, 8, 10])); |
输入
输出
The text was updated successfully, but these errors were encountered: