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
- Leetcode 3. Longest Substring Without Repeating Characters The Solution of Python and Javascript
- solution of LeetCode 3. Longest Substring Without Repeating Characters
- [LeetCode Solution]3.Longest Substring Without Repeating Characters
- leetcode-Length of the longest substring without repeating characters
- Leetcode -- Python -- Longest Substring Without Repeating Characters
- 【Leetcode】【python】Longest Substring Without Repeating Characters
- LeetCode 3. Longest Substring Without Repeating Characters (C++/python)
- 3.Longest Substring Without Repeating Characters Leetcode Python
- [Leetcode]3. Longest Substring Without Repeating Characters @python
- Leetcode题解(Python): 3.Longest Substring Without Repeating Characters
- [leetcode: Python]3. Longest Substring Without Repeating Characters
- LeetCode 3. Longest Substring Without Repeating Characters题解python
- 【leetcode】3. Longest Substring Without Repeating Characters(Python & C++)
- LeetCode #3 Longest Substring Without Repeating Characters C# Solution
- [LeetCode]3.Longest Substring Without Repeating Characters
- LeetCode 3.Longest Substring Without Repeating Characters
- LeetCode --- 3. Longest Substring Without Repeating Characters
- [Leetcode] 3. Longest Substring Without Repeating Characters
- 深圳搬家公司 怎样做有更好的生意
- java中的经典问题解答
- django连接mysql数据库和操作数据库
- 【算法】用c/c++求两正整数的最大公约数
- python多进程多线程
- Leetcode 3. Longest Substring Without Repeating Characters The Solution of Python and Javascript
- 浙江省选day1第二天
- [js]Javascript中各种宽高、位置总
- 2017浙江省选一试第三天游记
- Redis-3.2.8的集群安装部署
- [字符串操作]poj 1274 展开字符串
- QTableWidget操作之上移,下移,删除
- jsp使用servlet实现验证码
- 移动端 Tips插件代码