Reputation: 1582
Need find the length of the longest substring that consists of the same letter. For example, line "aaabbcaaaa" contains four substrings with the same letters "aaa", "bb","c" and "aaaa".
i found two way to do that, but all not so good;
At first way i don't make check previos similar letters here sdsffffse
;
Because i check only current element and second element if(line[i] === line[i+1])
.
At second way i fail when i try to check how many aa
i found in that string abababaab
but in object i add all a
letters and length = 5;
function longRepeat(line) {
let count = {};
let letter = [];
for (let i=0; i<line.length; i++) {
count[line[i]] = i;
if(line[i] === line[i+1]){
letter.push([line[i], line[i+1]])
}
}
/*
second way
for (let x of line) {
count[x] = ~~count[x] + 1;
} */
return letter;
}
console.log(longRepeat('sdsffffse')); f = 4
console.log(longRepeat('ddvvrwwwrggg')); = 3
console.log(longRepeat('abababaab')); // last two a = 2
Upvotes: 0
Views: 539
Reputation: 1
#python
def long_repeat(line):
line = line.lower()
max = 1
if len(line) == 0:
return 0
for i in range(0, len(line) - 1):
count = 1
while line[i] == line[i + 1]:
count += 1
if max < count:
max = count
if i < len(line) - 2:
i += 1
else:
break
return max
Upvotes: 0
Reputation:
If you don't mind using regular expressions.
function func(line) {
let reg = /(\w)\1+/g;
let longest = line.match(reg).sort((a, b) => {
a.length - b.length
}).pop();
console.log(line + ' : ' + longest);
}
func('ddvvrwwwrggg');
func('sdsffffse');
func('abababaab');
func('aaabbcaaaa');
func('aaaasdfbbbbyyyweryyyuurweuuuuuu');
/(\w)\1+/g
will match a sequence of the same character, using the match()
method we get all the sequences, sort them by length, and get the last item in the array, i didn't know what to do in case of equal length, so i'll leave that you, i'm merely presenting an idea, and it's for you to improve it :)
Upvotes: 1
Reputation: 2462
Possible solution:
function longestSubstr(str) {
if (!str) return 0
let maxL = 1
let curL = 1
for (let i = 0; i < str.length - 1; i++) {
let cur = str[i]
let next = str[i + 1]
if (cur === next) {
curL++
} else {
if (maxL < curL) maxL = curL
curL = 1
}
}
if (maxL < curL) maxL = curL
return maxL
}
console.log(longestSubstr("abababaab")) // 2
Upvotes: 1