How to find the longest substring that consists of the same char?

浪尽此生 提交于 2021-02-20 02:37:57

问题


Now I try to solve task about finding length the longest substring that consists of the same char. For example, I have a string yyuuufhvksoooo, then I will get result 4.

I wrote this code, here it is:

function longRepeat(line) {
  if (line.length > 0) {
    var count = 1;
    var max = 1;
  }
  for (let i = 0; i < line.length - 1; i++) {
    if (line[i] == line[i + 1]) {
      count++;
      if (count > max) max = count;
    } else {
      count = 1;
    }
  }
  return max;
}

It is work. But when I test this code with big string, framework from site, where I found this task, gives me error You process has been killed because of using too much resources. How can I do my code more effective?


回答1:


You could use a nested loop with a second variable j to move forward from the current i position until a non-matching character is found. Then if the difference between j and i is greater than the max, assign it as the max.

The next value of i after each iteration becomes the value of j, since it already did the work of moving forward at least one position.

function longRepeat(line) {
  if (!line.length) {
    return 0
  }
  var max = 1;
  for (let i = 0, j = 0; i < line.length - 1; i = j) {
    for (j = i + 1; j < line.length && line[j] == line[i]; j++) {
      // No more work to do here
    }

    if (j - i > max) {
      max = j - i;
    }
  }
  return max;
}

console.log(longRepeat("yyuuufhvksoooo"));

The problem you're referring to in the question is unclear. You can try batching the process, but hard to know exactly what the solution is to that problem without more info.


Here's a version that performs fewer assignments and comparisons, which may be a little more efficient.

function longRepeat(line) {
  if (!line.length) {
    return 0
  }

  let max = 1;
  let i = 0;
  while (i < line.length-1) {
    const j = i;
    while (line[++i] == line[j]) {
      // No more work to do here
    }

    if (i - j > max) {
      max = i - j;
    }
  }
  return max;
}

console.log(longRepeat("yyuuufhvksoooo"));



回答2:


I realise you have already accepted an answer, but there is maybe still room for improvement for really large strings where on average you can expect ranges with same characters to get longer.

The idea is that when you already have a maximum length of a same-character sequence that is say 10, you can jump forward with steps of 5 as long as the character you find there is different from the previous one. You can do this because there is no way to fit in a sequence of 11 same characters when you know the characters at every jump of 5 are different.

In a random, long input string, this might mean you will be able to skip a lot of characters that way.

Of course, when such a test shows that the character is the same, you'll still have to go back and check how long the sequence really is. But this just means you'll be visiting characters that you would also have visited in the accepted algorithm. So there is hardly a loss there. The cost is in the extra "jump" test. In the worst case you would find the same character at every jump of 5, and still find that there is no longer sequence of the same character. But with random input, with 26 possible characters per position (or more), it is more likely they are different, and that you can jump a lot.

Here is the code:

function longRepeat(line) {
  if (!line.length) {
    return 0;
  }
  var max = 1, jump = 1, i, j, k, prev;
  for (i = 0, j = 0; i < line.length - 1; i = j) {
    prev = line[i];
    j = i + jump;
    if (line[j] !== prev) continue; // quick jump
    for (j = i + 1; j < line.length && line[j] === prev; j++) {
      // No more work to do here
    }
    for (k = i - 1; line[k] === prev; k--) { 
      // Looking backwards: no work either
    }
    if (j - k - 1 > max) {
      max = j - k - 1;
      jump = (max+1) >> 1;
    }
  }
  return max;
}

console.log(longRepeat("yyuuufhvksoooo"));



回答3:


Write a function with inbuilt javascript features

  • Regex match to match sub-string of same char & split into an array
  • Map the array and get the lengths of each word
  • Find the maximum of the word lengths

var findMaxLength = function(inputString){
		var arrChuncks = inputString.match(/(.)\1*/g);
		var arrChunkLengths = arrChuncks.map(function(i){return i.length})
		return Math.max.apply(null, arrChunkLengths)
}

var testString = "turpis venenatis porta. Maecenas et ultricies dui, ut accumsan metus. Duis ut odio at risus tincidunt scelerisque. Duis placerat efficitur posuere. Nam sit amet tincidunt purus. Maecenas urna nibh, imperdiet quis dui nec, congue maximus nisl. Vestibulum a magna pellentesque, ultricies libero id, porta lorem.Morbi eu ex mi. In pulvinar sit amet libero  felis.Pellentesque tellus dui, blandit vitae felis sed, rutrum volutpat tortor. Morbi consequat finibus leo quis porta. Aliquam varius ipsum in lorem varius mollis. Vivamus id ultricies tortor, sed rhoncus nisi. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuerebbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb cubilia Curae; Class aptent taciti sociosqu ad litora torquent per conubia nostra, ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccper inceptos himenaeos. Sed et massa in metus elementum sodales. Vestibulum id metus risus. Aliquam consequat at ante ut lobortis.Etiam vitae arcu et nisi laoreet gravida id id magna. Sed rutrum lacus ut enim vulputate facilisis. e platea dictumst. Donec rhoncus, ex at commodo volutpat, augue nulla rhoncus quam, ut pulvinar mi neque consectetur risus. Morbi tempor rhoncus mauris, sit amet tincidunt libero ultrices iaculis. Nulla erat dui, llis turpis non eros varius, mollis dictum neque vehicula. Aenean est felis, pellentesque non lectus vel, ultricies venenatis dui. Vivamus dictum lorem cursus hendrerit molestie. Aenean ornare  malesuada fames ac turpis egestas. Aliquam id bibendum turpis. Morbi in imperdiet elit.Sed in rhoncus purus. Nullam consequat nulla magna, in porttitor enim auctor feugiat. Nunc blandit, orci non vehicula malesuada, elit velit varius odio, id lobortis lectus purus in dui. Quisque massa nulla, convallis a mi vel, sagittis tincidunt lacus. ";

document.getElementById('output').innerHTML = findMaxLength(testString);
Max Length : 
<div id='output'></div>


来源:https://stackoverflow.com/questions/45907202/how-to-find-the-longest-substring-that-consists-of-the-same-char

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!