【leetCode】无重复字符的最长子串

题目地址 3. 无重复字符的最长子串 - 力扣(LeetCode) (leetcode-cn.com)

解题思路一:

  从字符串第一位开始计算,记录所有子集中,计算最长的那个子串长度;

  最主要是拿到所有子集,可以用两个循环做,外层的for语句记录当前循环起始位置1,2,3,4.......n;内层的就记录当前位开始的不重复字符串的长度,并记录。如果碰到重复字符串,那跳出内循环,开始下一个外循环应该就可以

 

解题思路二:

  用do,while语句,其实这个就是滑动窗口,相当于我碰到相同字符串后,我就重置开始循环的位置,这样的时间复杂度相对来说要少一些。代码如下

 

var lengthOfLongestSubstring = function (s) {
  let curLen = 0
  let curIndex = 0
  let longstr = ''
  let j = 0
  do {
    if (longstr.indexOf(s[j]) > -1) {
      if (s[j - 1] === s[j]) {
        curIndex = j
      } else {
        j = curIndex + 1
        curIndex++
      }
      longstr = ''
    } else {
      longstr = s.substring(curIndex, j + 1)
      if (longstr.length > curLen) {
        curLen = longstr.length
      }
      j++
    }
  } while (j <= s.length)
  return curLen
};

 

posted on 2021-12-15 22:48  chinesedon007  阅读(57)  评论(0)    收藏  举报