如何找到由相同字符组成的最长子字符串? [英] How to find the longest substring that consists of the same char?

查看:63
本文介绍了如何找到由相同字符组成的最长子字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我尝试解决有关查找长度由相同字符组成的最长子字符串的任务.例如,我有一个字符串 yyuuufhvksoooo ,那么我将得到结果 4 .

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?

推荐答案

您可以使用带有第二个变量 j 的嵌套循环从当前 i 位置向前移动直到找到不匹配的字符.然后,如果 j i 之间的差异大于最大值,则将其分配为最大值.

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.

每次迭代后,下一个 i 的值将成为 j 的值,因为它已经完成了至少向前移动一个位置的工作.

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"));

这篇关于如何找到由相同字符组成的最长子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆