Title: Longest string without repeating characters
Given a string, find the length of the smallest string that does not contain repeating characters.
Example:
Example 1:
Input: "abcabcbb" Output: 3 Explanation: Since the oldest string without repeating characters is "ABC", its length is 3.Copy the code
Example 2:
Input: "BBBBB" Output: 1 Explanation: Since the oldest string without repeating characters is "b", its length is 1.Copy the code
Example 3:
Input: "pwwkew" Output: 3 Explanation: Since the oldest string without repeating characters is "wke", its length is 3. Note that your answer must be the length of the substring, "pwke" is a subsequence, not a substring.Copy the code
Using the language JavaScript:
/ * * *@param {string} s
* @return {number}* /
var lengthOfLongestSubstring = function(s) {
var now=[];
var max = 0;
for(var i = 0; i<s.length; i++){var n = s.substring(i, i + 1);
if(now.includes(s[i])){
if(now.length > max){
max = now.length;
}
now += n;
var index = now.indexOf(n);
now = now.substring(index + 1);
}else{ now += n; }}return now.length > max ? now.length : max;
};
Copy the code
Analysis:
In this case, I entered the blind area of thinking at the beginning, and did not pass the result for a long time. Then I referred to other people’s Java method to pass. I started by iterating through the S string, incrementally adding each character in the string to an array, saving the length of the current array as soon as a duplicate character appeared, and then empting the array to replace the character. But one example I didn’t consider was KVKL. This example is supposed to be 2, but it turns out to be 3
Examples of errors:
/ * * *@param {string} s
* @return {number}* /
var lengthOfLongestSubstring = function(s) {
var max = [];
var num = [];
var j = 0;
if(s.length==0) {return 0;
}
for(var i=0; i<s.length; i++){if(max.includes(s[i])){
num[j] = max.length;
max = [];
max.push(s[i]);
j++;
}else{ max.push(s[i]); }}if(num.length>=max.length){
return Math.max.apply(null,num);
}else{
returnmax.length; }};Copy the code