给定一个字符串,找出不含有重复字符的最长子串的长度。
输入: "abcabcbb"
输出: 3
解释: 无重复字符的最长子串是 "abc",其长度为 3。
python
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
i = 0;j = 0;ans = 0
maps = {}
for j in range(len(s)):
if maps.__contains__(s[j]):
i = max(i,maps.get(s[j]))
ans = max(ans,j-i+1)
maps[s[j]] = j+1
return ans
java
class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length();
int i = 0,j = 0;
int ans = 0;
HashMap<Character,Integer> map = new HashMap<>();
for(i=0,j=0;j<n;j++){
if(map.containsKey(s.charAt(j))){
i = Math.max(map.get(s.charAt(j)),i);
}
ans = Math.max(j-i+1,ans);
map.put(s.charAt(j),j+1);
}
return ans;
}
}
网友评论