I want to know the longest length of consecutive items of X there are in Y. I will provide you an item (Y), and a key to search for (X). Return the length of the longest segment of consecutive keys (X) in Y.
Rules:
The item will be either an integer or string data type.
The key will be an integer or string data type.
The return value will be an integer data type.
If the key does not appear in the number, return 0.
Example1:
items = 90000;
key = 0;
return value: 4;Example2:
items = 'abcdaaadse';
key = 'a';
return value: 3;
(요약) key
값이 items
에서 가장 길게 연속되는 길이를 구하라.
function getConsectiveItems(items, key){ let answer = 0; items = typeof items === 'string' ? items : `${items}`; key = typeof key === 'string' ? key : `${key}`; const length = items.length; for(let i = 0; i < length; i++) { if(items[i] === key) { let count = 1; for(let j = i + 1; j < length; j++) { if(items[j] !== key) break; count++; } answer = answer < count ? count : answer; } } return answer; }
items
에서key
가 시작 되는 위치를 찾고, 거기서부터 몇 번 연속되는지 카운팅해서return
.