Problem description
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.
Code (C++)
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int len = s.length();
set<char> co;
int left = 0;
int right = 0;
int res = 0;
while(right < len) {
if(co.find(s[right]) != co.end()) {
co.erase(s[left]);
left++;
} else {
co.insert(s[right]);
right++;
res = res > right - left ? res : right - left;
}
}
return res;
}
};
Code (Java)
class Solution {
public int lengthOfLongestSubstring(String s) {
int len = s.length();
Set<Character> co = new HashSet<Character>();
int left = 0;
int right = 0;
int res = 0;
while(right < len) {
if(co.contains(s.charAt(right)) == true) {
co.remove(s.charAt(left));
left++;
} else {
co.add(s.charAt(right));
right++;
res = Math.max(res, right - left);
}
}
return res;
}
}
Analysis
- 注意解题思路。
网友评论