Leetcode 3. Longest Substring Without Repeating Characters The Solution of Python and Javascript

来源:互联网 发布:道路平面图绘制软件 编辑:程序博客网 时间:2024/05/16 10:06

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given “abcabcbb”, the answer is “abc”, which the length is 3.

Given “bbbbb”, the answer is “b”, with the length of 1.

Given “pwwkew”, the answer is “wke”, with the length of 3. Note that the answer must be a substring, “pwke” is a subsequence and not a substring.

Subscribe to see which companies asked this question.

Python:

class Solution(object):    def lengthOfLongestSubstring(self, s):        """        :type s: str        :rtype: int        """        table,beg,length={},0,0#定义字典,最长字串起始位置和最长长度        for index,n in enumerate(s):#遍历s            if n not in table or beg>table[n]:#当字符n不在字典中或者n在字典中但是已经在起始位置之后时                length=max(length,index-beg+1)#计算最长长度            else:                beg=table[n]+1#否则重新设置当前最长字符串起始位置            table[n]=index#将当前值存入字典        return length

主要思想是建立一个字典,实时读取最长length

Javascript:

/** * @param {string} s * @return {number} */var lengthOfLongestSubstring = function(s) {    let a=[];    let len=0;    for (let i=0;i<s.length;i++) {        let index=a.indexOf(s[i]);//返回数组a中s[i]的首次出现位置        if (index>=0) {//如果数组中s[i]存在,删除数组中s[i]以及之前的值            a.splice(0,index+1);        }        a.push(s[i]);//将当前s[i]存入数组        len=Math.max(a.length,len);//计算最长长度    }    return len;};

由于js有indexOf的操作,可以返回某个指定的字符串值在字符串中首次出现的位置,理解起来更简单。

0 0
原创粉丝点击