最长的子串非重复字符javascript

时间:2017-03-24 14:44:25

标签: javascript

问题请求"给定一个字符串,找到最长的非重复子字符串而不重复字符"。我有点难过为什么返回我的代码不适用于字符串" dvdf"例如。这是我的代码:

function lengthOfLongestSubstring(check) {
    var letters = check.split("");
    var max = 0;
    var result = [];
    for (var i = 0; i < letters.length; i++) {
        var start = i
        if (result.indexOf(letters[i]) === -1) {
            result.push(letters[i])
        } else {
            i = i - 1
            result = []
        }
        if (max === 0 || max < result.length) {
            max = result.length
        }
    }
    return max
}

10 个答案:

答案 0 :(得分:1)

通过将result数组替换为存储每个遇到的字符的最后一个索引的映射,您可以修改循环体以跳回到相同字符的最后一个索引之后的一个,并从那里继续搜索刚刚从当前位置重新启动当前i = i - 1,在'dvdf'

等情况下失败

以下是您的代码,其中包含更改以容纳地图以代替数组:

&#13;
&#13;
function lengthOfLongestSubstring(check) {
  var letters = check.split("");
  var max = 0;
  var result = new Map();
  var start = 0;
  
  for (var i = 0; i < letters.length; i++) {
    if (!result.has(letters[i])) {
      result.set(letters[i], i);
    } else {
      i = result.get(letters[i]);
      result.clear();
    }
    
    if (max < result.size) {
      max = result.size;
    }
  }
  return max;
}

// Example:
console.log(lengthOfLongestSubstring("dvdf")); // 3
&#13;
&#13;
&#13;

答案 1 :(得分:1)

这是使用滑动窗口和HashMap的解决方案。

var lengthOfLongestSubstring = function(str) {
  if (!!!str.length || typeof str !== 'string') return 0;

  if (str.length == 1) return 1;
  let hashTable = {};
  let longestSubstringLength = 0;
  let start = 0;
  for (let i = 0; i < str.length; i++) {
    if (hashTable[str[i]] !== undefined && hashTable[str[i]] >= start) {
      start = hashTable[str[i]] + 1;
    }
    hashTable[str[i]] = i;
    longestSubstringLength = Math.max(longestSubstringLength, (i - start + 1))
  }
  return longestSubstringLength;
}

答案 2 :(得分:1)

今天(2021 年 1 月 7 日)这是今天的 Leetcode 问题。我最初使用的解决方案与所选答案非常相似。性能还可以,但在查看答案解决方案文档后,我使用滑动窗口技术重写了我的答案(示例仅在 Java 和 Python 中),因为我很好奇这会带来多大的性能改进。它的性能稍微提高了( 144 毫秒与 160 毫秒)并且具有较低的内存占用(42 mb 与 44.9 mb):

function lengthOfLongestSubstring(s: string): number {
    let stringLength = s.length;
    let maxLength = 0;
    const charMap = new Map();
    let pos = 0;

    for (let i = 0; i < stringLength; i++) {
        if (charMap.has(s[i])) {
            pos = Math.max(charMap.get(s[i]), pos);
        }

        maxLength = Math.max(maxLength, i - pos + 1);
        charMap.set(s[i], i + 1);
    }
    return maxLength;
}

console.log(lengthOfLongestSubstring("dvdf"));

答案 3 :(得分:1)

试试这个:

function lengthOfLongestSubstring (str) {
  const map = new Map();
  let max = 0;
  let left = 0;
  for (let right = 0; right < str.length; right++) {
    const char = str[right];
    if (map.get(char) >= left) left = map.get(char) + 1;
    else max = Math.max(max, right - left + 1);
    map.set(char, right);
  }
  return max;
}

答案 4 :(得分:0)

将i重置为i -1不正确。你需要在for循环中使用另一个循环。你尝试这样的事情(我没有仔细检查索引)。

function lengthOfLongestSubstring(check){
    var letters = check.split("");
    var max = 0;
    for (var i = 0; i < letters.length; i++) {
        var result = [];
        var j = i;
        for(;j < letters.length; j++) {
            if (result.indexOf(letters[j]) === -1) {
                result.push(letters[j]);
            } else {
                break;
            }        
        }
        if(j - i > max) {
            max = j - i;
        }
    }
    return max;
}

答案 5 :(得分:0)

此实现为"dvdf"提供了正确的结果。

它为current_string添加了字符,而没有重复。当您发现重复切割current_string到重复点时。 max是任何时候current_string的最大长度。这个逻辑对我来说似乎是正确的,所以我认为这是正确的。

function lengthOfLongestSubstring(string) {
    var max = 0, current_string = "", i, char, pos;

    for (i = 0; i < string.length; i += 1) {
        char = string.charAt(i);
        pos = current_string.indexOf(char);
        if (pos !== -1) {
            // cut "dv" to "v" when you see another "d"
            current_string = current_string.substr(pos + 1);
        }
        current_string += char;
        max = Math.max(max, current_string.length);
    }
    return max;
}

lengthOfLongestSubstring("dvdf"); // 3

每轮current_string的值为"", "d", "dv", "vd", "vdf"

答案 6 :(得分:0)

您可以尝试滑动窗口模式来解决此问题。

function lengthOfLongestSubstring(str) {
  let longest = 0;
  let longestStr = "";
  let seen = {};
  let start = 0;
  let next = 0;

  while (next < str.length) {
    // Take current character from string
    let char = str[next];

    // If current character is already present in map
    if (seen[char]) {
      // Check if start index is greater than current character's last index
      start = Math.max(start, seen[char]);
    }

    // If new substring is longer than older
    if (longest < next - start + 1) {
      longest = next - start + 1;
      // Take slice of longer substring
      longestStr = str.slice(start, next + 1);
    }
    // Update current characters index
    seen[char] = next + 1;
    // Move to next character
    next++;
  }

  console.log(str, "->", longestStr, "->", longest);
  return longest;
}

lengthOfLongestSubstring("dvdfvev");
lengthOfLongestSubstring("hello");
lengthOfLongestSubstring("1212312344");

答案 7 :(得分:0)

使用映射方法查找最长的唯一子字符串

var str = "aaabcbdeaf";
var start = 0;
var map = new Map();
var maxLength = 0;
var longStr = '';

for(next =0; next< str.length ; next++){
if(map.has(str[next])){
  map.set(str[next],map.get(str[next])+1);
  start = Math.max(start,map.get(str[next]));
}
if(maxLength < next-start+1){
  maxLength = next-start+1;
  longStr = str.slice(start,next+1);
}
 map.set(str[next],next);
}
console.log(longStr);

答案 8 :(得分:0)

您可以尝试以下方法:

function maxSubstring(s) {
  const array = []
  const lengthS = s.length
  const pusher = (value) => {
    if (value !== '') {
      if (array.length > 0) {
        if (array.indexOf(value) === -1) {
          array.push(value)
        }
      } else {
        array.push(value)
      }
    }
  }
  pusher(s)
  for (const [index, value] of s.split('').entries()) {
    let length = lengthS
    let string = s
    const indexO = s.indexOf(value)
    pusher(value)
    while (length > indexO) {
      pusher(string.slice(index-1, length + 1))
      length = --length
    }
    string = s.slice(index, lengthS)
  }
  array.sort()
  return array.pop()
}

console.log(maxSubstring('banana'))
console.log(maxSubstring('fgjashore'))
console.log(maxSubstring('xyzabcd'))

答案 9 :(得分:0)

在不使用 MAP() 的情况下查找最长的唯一子字符串。只是简单的 slice()。 同样可以用于返回最长的唯一字符串。

只需替换“return max => return str”

const string = "dvdf";

var lengthOfLongestSubstring = function() {
if(string.length == 1) return 1;
if(string.length == 0) return 0;

let max = 0,i =  0, str = "";

while(i < string.length){
    const index = str.indexOf(string.charAt(i));
    if(index > -1) {
        // s = "fiterm".slice(1,4) => ite
        str = str.slice(index + 1, string.length);
    }
    str += string.charAt(i);
    max = Math.max(str.length, max);
    i++;
}
  return max;
};