Find longest substring without repeating characters

前端 未结 30 2569
轻奢々
轻奢々 2020-12-12 18:07

Given a string S of length N find longest substring without repeating characters.

Example:

Input:

30条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-12 18:56

    This is my solution. Hope it helps.

      function longestSubstringWithoutDuplication(str) {
          var max = 0;
    
          //if empty string
          if (str.length === 0){
            return 0;
          } else if (str.length === 1){ //case if the string's length is 1
            return 1;
          }
    
          //loop over all the chars in the strings
          var currentChar,
              map = {},
              counter = 0; //count the number of char in each substring without duplications
          for (var i=0; i< str.length ; i++){
            currentChar = str.charAt(i);
    
            //if the current char is not in the map
            if (map[currentChar]  == undefined){
              //push the currentChar to the map
                  map[currentChar] = i;
                  if (Object.keys(map).length > max){
                     max = Object.keys(map).length;
                  }
            } else { //there is duplacation
              //update the max
              if (Object.keys(map).length > max){
                max = Object.keys(map).length;
              }
              counter = 0; //initilize the counter to count next substring
              i = map[currentChar]; //start from the duplicated char
              map = {}; // clean the map
            }
          }
    
    
         return max;
        }
    

提交回复
热议问题