This is the third day of my participation in the August More text Challenge. For details, see: August More Text Challenge

preface

String processing plays an important role in either front end or back end. Processing string is a skill that everyone must master. Here is a simple string related algorithm problem.

LeetCode The oldest string with no duplicate characters

Topic describes

Given a string s, find the longest string that does not contain repeating characters.

Example 1:

Input: s = “abcabCBb”

Output: 3

Explanation: Since the oldest string with no duplicate characters is “ABC”, its length is 3.

Example 2:

Input: s = “BBBBB”

Output: 1.

Explanation: Since the oldest string with no duplicate characters is “b”, its length is 1.

Example 3:

Input: s = “pwwkew”

Output: 3

Explanation: Since the oldest string with no duplicate 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.

Example 4:

Input: s = “”

Output: 0

Their thinking

  • First declare two arrays, a noRepeat empty to hold non-repeating characters, and a sArray to hold strings converted from split
  • Each item in the sArray array is identified by forEach (norepeat.includes (item) is used to determine if the item exists in noRepeat).
  • If the result is false, it is stored in the array noRepeat
  • If true, determine the size of maxLength and noRepeat. If maxLength
  • Remember to make the maxLength and noRepeat. Length judgment again at the end (because there may have been no else at some point in time, or in extreme cases, there may have been no else in the first place)
  • Finally, return maxLength, which is the result
  • Remember to consider the case where the input is null

The code is as follows:

/ * * *@param {string} s
 * @return {number}* /
var lengthOfLongestSubstring = function(s) {
    var sArray = s.split(' ')
    var  noRepeat = []
    var  maxLength =0 
    sArray.forEach((item,index) = > {
        if(! noRepeat.includes(item)){ noRepeat.push(item) }else{
            if(maxLength<noRepeat.length){
                maxLength= noRepeat.length
            }
            var index = noRepeat.indexOf(item)
            noRepeat =noRepeat.slice(index+1)
            noRepeat.push(item)
        }
    })
    if(maxLength<noRepeat.length){
                maxLength= noRepeat.length
            }
    return maxLength
};
Copy the code

conclusion

String processing is interesting because when you’re dealing with strings, you have to think about what each case is supposed to be dealing with, and you go over and over and over and over again, and refine the cases that you might not have considered, and you get the result that you want.

There should be a more convenient and efficient method, welcome the leaders to give advice.