# 3. Longest Substring Without Repeating Characters

82人阅读 评论(0)

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.

class Solution {
public:
int lengthOfLongestSubstring(string s) {

vector<int> charIndex(256, -1);
int longest = 0, lastlen = 0;

for(int i=0; i<s.size(); i++){
lastlen = max(charIndex[s[i]]+1, lastlen);  //上一次出现当前元素的下标
charIndex[s[i]] = i; //将当前元素出现的位置保存到数组中
longest = max(longest, i-lastlen+1);
}

return longest;
}
};

java版：20ms

public class Solution {
public int lengthOfLongestSubstring(String s) {

if(s.length()==0) return 0;
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int longest = 0;
for(int i=0, j=0; i<s.length(); i++){
if(map.containsKey(s.charAt(i))){
j = Math.max(j, map.get(s.charAt(i))+1);
}
map.put(s.charAt(i), i);
longest = Math.max(longest, i-j+1);
}
return longest;
}
}


public class Solution {
public int lengthOfLongestSubstring(String s) {

int i=0, j=0, longest = 0;
Set<Character> set = new HashSet<>();

while(j<s.length()){
if(!set.contains(s.charAt(j))){
longest = Math.max(longest, set.size());
}else{
set.remove(s.charAt(i++));
}
}
return longest;
}
}


0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：49772次
• 积分：920
• 等级：
• 排名：千里之外
• 原创：8篇
• 转载：242篇
• 译文：0篇
• 评论：5条
文章分类
阅读排行